我长期以来一直坚持这个问题
我必须合并3个表并对不同的值进行计数
我有3张桌子
1.User_me
profileId(String)
响应(int 1或0)
2.Profiles
profileId(String)
idLocation(int)
3.lookup_location
id(int)
location(String)
我可以加入User_me和Profiles ON User_me.profileId = Profiles.profileId
我可以加入Profiles和lookup_location ON Profiles.idLocation = lookup_location.id
在“个人档案”下,我需要计算idLocation的不同值的数量,其中User_me.profileId = Profiles.profileId
我还需要计算具有User_me.responded = 1
我有这个:
SELECT lookup.location, count(*) as total
FROM User_me user
JOIN Profiles
ON user.profileId= profiles.profileId
JOIN lookup_location lookup
ON profiles.idLocation = lookup.id
GROUP BY profiles.idLocation
但是我仍然需要让列给我一个User_me.responded = 1的计数 像:
SELECT lookup.location, count(*) as total, count(*) responded
答案 0 :(得分:1)
如果我正确理解您的问题,您可以在case
聚合中发表count
声明:
SELECT lookup.location, count(*) as total,
count(case when user.responded = 1 then 1 end) as responded
FROM User_me user
JOIN Profiles
ON user.profileId= profiles.profileId
JOIN lookup_location lookup
ON profiles.idLocation = lookup.id
GROUP BY profiles.idLocation
由于您使用的是MySQL
,因此您还可以使用sum(user.responded = 1)
之类的内容。