gpt4 book ai didi

sql-server - 如何将结果合并到一条线上

转载 作者:行者123 更新时间:2023-12-01 00:36:38 25 4
gpt4 key购买 nike

我有一个查询,我正在尝试使用 SQL Server 将其合并到 1 行。它一直迫使我按 Frequency 列分组,但我只想按 UserId 分组。谁能告诉我我做错了什么。

代码:

SELECT userid, frequency,
(select count(frequency) where frequency = 1) AS Onetime,
(select count(frequency) where frequency = 2) AS Daily,
(select count(frequency) where frequency = 3) AS Weekly,
(select count(frequency) where frequency = 4) AS Fortnightly,
(select count(frequency) where frequency = 5) AS Monthly,
(select count(frequency) where frequency = 6) AS Quarterly,
(select count(frequency) where frequency = 7) AS SemiAnnual,
(select count(frequency) where frequency = 8) AS Annual
FROM AppTasks
where userid = 'userid@gmail.com'
group by UserID, Frequency

数据:

image

最佳答案

你能试试这个吗?

SELECT userid,
SUM(CASE WHEN frequency = 1 THEN 1 ELSE 0 END) AS Onetime,
SUM(CASE WHEN frequency = 2 THEN 1 ELSE 0 END) AS Daily,
SUM(CASE WHEN frequency = 3 THEN 1 ELSE 0 END) AS Weekly,
SUM(CASE WHEN frequency = 4 THEN 1 ELSE 0 END) AS Fortnightly,
SUM(CASE WHEN frequency = 5 THEN 1 ELSE 0 END) AS Monthly,
SUM(CASE WHEN frequency = 6 THEN 1 ELSE 0 END) AS Quarterly,
SUM(CASE WHEN frequency = 7 THEN 1 ELSE 0 END) AS SemiAnnual,
FROM AppTasks
where userid = 'userid@gmail.com'
group by UserID;

关于sql-server - 如何将结果合并到一条线上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48805487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com