如何使用sql以下面的格式获得输出? 我可以使用case sum来完成它,但是我无法在同一行中获得唯一的用户数。
id unique_users male_count female_count
101 3 1 2
201 1 0 1
.
.
答案 0 :(得分:3)
select id,
count(distinct user) as unique_users,
sum(case when gender = 'M' then 1 else 0 end) as male_count,
sum(case when gender = 'F' then 1 else 0 end) as female_count
from your_table
group by id
答案 1 :(得分:2)
替代方案计算不同的男性和女性。
SELECT
ID,
COUNT(DISTINCT "USER") AS unique_users,
COUNT(DISTINCT DECODE(gender,'M',"USER")) AS male_count,
COUNT(DISTINCT DECODE(gender,'F',"USER")) AS female_count
FROM your_table
GROUP BY ID
ORDER BY ID;
同样但没有Oracle特定的DECODE功能。
SELECT
ID,
COUNT(DISTINCT "USER") AS unique_users,
COUNT(DISTINCT CASE gender WHEN 'M' THEN "USER" ELSE NULL END) AS male_count,
COUNT(DISTINCT CASE gender WHEN 'F' THEN "USER" ELSE NULL END) AS female_count
FROM your_table
WHERE ID = 101
GROUP BY ID
ORDER BY ID;
我引用了“USER”,因为它在Oracle中具有特定含义。