oracle 了解如何在sql中添加列而不必按列分组

y1aodyip  于 2022-12-11  发布在  Oracle
关注(0)|答案(1)|浏览(175)

I have the following query:

SELECT DISTINCT
    status,
    CASE
        WHEN status = 0 THEN 'bla' 
        WHEN status = 2 THEN 'bla1'  
    END AS "description" ,
    COUNT(*) AS total     
FROM
    TRANSACTIONS 
WHERE 
    status != 1 
GROUP BY
    status

which displays:
| Status | DESCRIPTION | TOTAL |
| ------------ | ------------ | ------------ |
| 0 | bla | 29 |
| 2 | bla1 | 70 |
| 3 | (null) | 12 |
| 4 | (null) | 85 |
now lets assume I have a table called Status_Codes which provides the Description itself, for example:
| Status | DESCRIPTION |
| ------------ | ------------ |
| 0 | bla |
| 2 | bla1 |
I want to remove the case statement from my query that explicitly attaching the descriptions I need, and add my FROM clause the Status_Codes table, and to add Status_Codes.Description to my select. That action cannot be done simply because I use an aggregate function in my select statement and I'd have to group by the same column( which is not something I want). Im not sure on how to approach that problem, was thinking maybe it has something to do with partition by, but even if thats the case I dont know how to implement it in my query.
Any advices, Enlightments and whatnot will be appreciated. thanks.

u2nhd7ah

u2nhd7ah1#

为什么要在group by子句中添加另一列呢?这是最简单、最有效的方法。

SELECT t.status, c.description, COUNT (*) AS total
    FROM transactions t JOIN status_codes c ON c.status = t.status
   WHERE t.status != 1
GROUP BY t.status, c.description

如果你用不同的方式做,你期望得到什么好处?
顺便说一句,如果你有group by子句,你就不需要distinct

相关问题