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.
1条答案
按热度按时间u2nhd7ah1#
为什么要在
group by
子句中添加另一列呢?这是最简单、最有效的方法。如果你用不同的方式做,你期望得到什么好处?
顺便说一句,如果你有
group by
子句,你就不需要distinct
。