PostgreSQL选择列然后添加随机值

时间:2018-05-28 12:18:07

标签: sql postgresql

解决了!谢谢Gordon Linoff!

是否有可能在PostgreSQL中获得这样的查询结果?

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

“Total”行是3列的总和。

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

1 个答案:

答案 0 :(得分:0)

我猜这是一个聚合查询。如果是,请使用grouping sets(或rollup):

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