以下是我的查询:
select (
case when activity_type=3 then 'share_count_secret'
when activity_type=4 then 'download_count_secret'
when activity_type=5 then 'copy_count_secret' end
)as activity_type ,
count(distinct user_account_id_fk) as counts
from activities
where target_id = 522556
and activity_type in(3,4,5)
group by activity_type;
以下是上述查询的输出:
activity_type counts
share_count 2
download_count 2
但我想要输出:
share_count download_count
2 2
答案 0 :(得分:0)
您可以尝试使用conditional aggregation
select
count(case when activity_type=3 then user_account_id_fk end) as 'share_count_secret',
count(case when activity_type=4 then user_account_id_fk end) as 'download_count_secret'
count(case when activity_type=5 then user_account_id_fk end) as 'copy_count_secret'
from activities
where target_id = 522556 and activity_type in(3,4,5)
答案 1 :(得分:0)
如果您使用的是SQL Server(我也看到您也标记了MySQL)。您可以尝试透视
;WITH CTE
AS
(
SELECT
(
CASE
WHEN activity_type = 3 THEN 'share_count_secret'
WHEN activity_type = 4 THEN 'download_count_secret'
WHEN activity_type = 5 THEN 'copy_count_secret'
END
) AS activity_type,
COUNT(DISTINCT user_account_id_fk) AS counts
FROM activities
WHERE target_id = 522556
AND activity_type IN( 3, 4, 5 )
GROUP BY activity_type
)
SELECT
*
FROM CTE
PIVOT
(
SUM(counts)
FOR
activity_type IN
(
[share_count_secret],
[download_count_secret],
[copy_count_secret]
)
)PVT
答案 2 :(得分:-1)
我认为这段代码可以为您提供帮助:
select
(case when activity_type=3 then count(user_account_id_fk) else 0) as 'share_count_secret',
(case when activity_type=4 then count(user_account_id_fk) else 0) as 'download_count_secret',
(case when activity_type=5 then count(user_account_id_fk) else 0) as 'copy_count_secret'
from activities
where target_id = 522556 and activity_type in(3,4,5)