通过查询返回一组中的多个计数

时间:2019-11-14 19:18:37

标签: sql sql-server

我有2张桌子。用户表和首选项表。

Users
-UserId

Preferences
-PreferenceId
-UserId
-PreferenceType
-Enabled

我有一个查询要获取按位置分组的用户数:

SELECT u.Location, u.Count
FROM Users u
GROUP BY u.Location

我想按位置报告用户,但还要为每个PreferenceType包括一列(例如,有3种类型'pref1','pref2','pref3' 因此,目前我正在为每个PreferenceType进行这样的单独查询:

SELECT u.Location, u.Count
From Users u
    inner join Preferences p ON p.UserId = u.UserId
WHERE
    p.PreferenceType = 'pref1'
    and p.Enabled = 1
GROUP BY u.Location

是否可以将所有这些结合起来并得到如下结果集:

SELECT u.Location, u.Count, Pref1Count, Pref2Count, Pref3Count
From Users u
    inner join Preferences p ON p.UserId = u.UserId
WHERE

1 个答案:

答案 0 :(得分:2)

您可以使用条件聚合:

select u.Location, count(distinct u.Userid) as cnt,
       sum(case when p.PreferenceType = 'pref1' and p.Enabled = 1 then 1 else 0 end) as pref1,
       sum(case when p.PreferenceType = 'pref2' and p.Enabled = 1 then 1 else 0 end) as pref2,
       sum(case when p.PreferenceType = 'pref3' and p.Enabled = 1 then 1 else 0 end) as pref3,
From Users u left join
     Preferences p 
     on p.UserId = u.UserId
group by u.Location;