简体   繁体   中英

PostgreSQL Select Columns Then Add Random Value

SOLVED! Thanks Gordon Linoff!

Is it possible to get query result like this in PostgreSQL?

UserName | Count |
Sukri    |   1   |
Azis     |   2   |
Adit     |   1   |
Total    |   4   |

The row "Total" value is the sum of 3 columns.

SELECT 
CASE 
    WHEN (res."UserName"IS NULL OR res."UserName" = '') THEN 'TOTAL' 
    ELSE res."UserName"
END AS "UserName",
res."Count"
FROM
(
    SELECT "UserName", count("UserName") AS "Count"
    FROM "Ticket"
    GROUP BY GROUPING SETS ( ("UserName"), () ) ORDER BY "UserName"
) AS res

I am going to guess this is an aggregation query. If so, use grouping sets (or rollup ):

select coalesce(username, 'Total') as userid, count(*) as cnt
from t
group by grouping sets ( (username), () );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM