我一直试图用联盟完成这项工作,加入同一个表并嵌套选择,但我无法得到我需要的结果。
所以,开始:我需要的所有数据都在 table1 中,其短版本结构如下:
ownerID varchar(25)
supervisorID varchar(25)
statusID int
样本数据是:
john.smith | joe.blogs | 1
john.smith | joe.blogs | 1
john.smith | joe.blogs | 1
john.smith | joe.blogs | 2
jane.doe | joe.blogs | 1
jane.doe | joe.blogs | 1
jane.doe | joe.blogs | 1
jane.doe | joe.blogs | 1
billy.bob | mary.jane | 1
billy.bob | mary.jane | 2
我希望得到的,在伪sql中将是:
SELECT ownerID, COUNT(*) as CountOne, COUNT(*) as CountTwo
FROM table1
WHERE supervisorID='joe.blogs'AND statusID=1
OR supervisorID='joe.blogs'AND statusID=2
GROUP BY ownerID
产生以下结果:
userID | countOne | countTwo
----------------------------------
john.smith | 3 | 1
----------------------------------
jane.doe | 4 | 0
显然伪SQL没有权利工作,但就像我说我尝试使用UNION,JOIN在同一张桌子上,嵌套选择,并询问谷歌但我生产的任何东西都不会给我所需的结果:(
数据库正在使用PostreSql。
答案 0 :(得分:1)
您可以使用SUM而不是COUNT,只汇总与您需要的statusId匹配的值 - 对于CountOne - >状态= 1,对于CountTwo - >状态= 2:
SELECT ownerId,
SUM(CASE WHEN statusId = 1 THEN 1 ELSE 0 END),
SUM(CASE WHEN statusId = 2 THEN 1 ELSE 0 END)
FROM table1
WHERE supervisorId = 'joe.blogs'
GROUP BY ownerId
希望它有所帮助。
答案 1 :(得分:0)
试试这个
select ownerID ,
sum(case when statusID =1 then 1 else 0 end) as countOne,
sum(case when statusID =2 then 1 else 0 end) as countTwo
from table1
group by ownerID