SQL using COUNT and CASE for related table - error is returned

故事扮演 提交于 2020-01-07 04:55:08

问题


I have table T1:

ID  GROUPINFO    STATUS
1   GROUP1       NEW
2   GROUP1       INPROG
3   GROUP2       INPROG

I have table T2 also

T2ID    T1ID  STATUS
 1       1      NEW
 2       2      NEW
 3       2      VENDOR
 4       3      NEW
 5       3      VENDOR

I want to count by group how many of those records have the status NEW, and how many of those records were in the status VENDOR (information from T2 table)

This SQL works

SELECT T1.GROUPINFO,
count (case when T1.status='NEW' then 1 end) as New
FROM T1
GROUP BY T1.GROUPINFO

However when I try to add how many of those records were in the VENDOR status I am getting an error:

SELECT T1.GROUPINFO,
count (case when T1.status='NEW' then 1 end) as New,
count (case when T1.ID in (select T2.ID from T2 where T2.status='VENDOR') then 1 end) as Vendor
FROM T1
GROUP BY T1.GROUPINFO

I am getting an error:

Bad Plan; Unresolved QNC found

I am not sure what I am doing wrong and how should I organize my SQL query so I could get this result for this example:

GROUPINFO   NEW   VENDOR
GROUP1       1     1
GROUP2       0     1

If ID exists multiple times in T2 it should only be counted 1 time because this is one record for which I want to check if it was in that status or not.

Update: I also tried EXISTS:

SELECT T1.GROUPINFO,
count (case when T1.status='NEW' then 1 end) as New,
count (case when exists (select 1  from T2 where T2.ID=T1.ID and T2.status='VENDOR') then 1 end) as Vendor
FROM T1
GROUP BY T1.GROUPINFO

but again having an SQL error: regarding the ID column

Update: I also tried EXISTS and JOIN:

SELECT T1.GROUPINFO,
count (case when T1.status='NEW' then 1 end) as New,
count (case when exists (select 1  from T2 where T2.ID=T1.ID and T2.status='VENDOR') then 1 end) as Vendor
FROM T1 LEFT OUTER JOIN T2 ON T1.ID=T2.ID
GROUP BY T1.GROUPINFO

but again having an SQL error: regarding the ID column


回答1:


select T3.Groupinfo,
count (distinct(case when t3.status="NEW" then t3.ID end)) as new,
count (distinct(case when t3.status_1 ="VENDOR" then t3.id end)) as Vendor
from 
(select t1.groupinfo,t1.id,t1.status,t2.t2id as id1,t2.status as status_1 from
t1 join t2
on t1.id=t2.t1id
) as t3
group by t3.Groupinfo;

Something Similar to this might help you i guess.



来源:https://stackoverflow.com/questions/43364018/sql-using-count-and-case-for-related-table-error-is-returned

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!