我有一个包含这样数据的表:
Id | Country | Desktop_User | Mobile_User
------------------------------------------
1 | USA | True | False
2 | Brazil | False |
3 | Mexico | | True
4 | India | True | True
5 | | False | True
我想要一个报告类型数据,我可以在哪里获得所有" Desktop_User" TRUE和ALL" Mobile_User" TRUE按国家/地区分组(考虑到某些记录可能具有国家/地区或Desktop_User或Mobile_User列的NULL值。如下所示:
Country | Desktop_User | Mobile_User
------------------------------------------
USA | 100 | 49
China | 50 | 10
India | 11 | 5
Brazil | 11 | 0
Mexico | 0 | 0
NO COUNTRY | 5 | 7
我希望按国家/地区按字母顺序排序数据 - 是否可能
到目前为止,我已创建此查询(如下所示),但我认为我的逻辑不正确,无法为桌面和移动用户获取所有TRUES和NULL值
我可以对数据进行排序的最佳方法是什么?
SELECT DISTINCT Country AS Country,
COUNT(Desktop_User) AS Desktop_User,
COUNT(Mobile_User) AS Mobile_User
FROM Contacts
WHERE Desktop_User = 'True'
OR Mobile_User = 'True'
GROUP BY Country
答案 0 :(得分:2)
尝试以下方法:
select Country AS Country
, SUM(case when Desktop_User = 'True' then 1 else 0 end) as Desktop_User_cnt
, SUM(case when Mobile_User = 'True' then 1 else 0 end) as Mobile_User_cnt
FROM Contacts
WHERE ((Desktop_User = 'True') OR (Mobile_User = 'True'))
group by Country
Order by Desktop_User_cnt desc
分组时不需要DISTINCT。