不同领域的SQL代码

时间:2018-07-31 17:05:18

标签: sql db2

我想知道是否有人可以帮助我进行此查询。

我有两个连接在一起的表(DDS2ENVR.QBO AND KCA0001.ORTS

QBO表的字段标记为NIIN AND RIC。 KCA0001.ORTS表具有一个名为SERVICE和OWN_RIC的字段。

我通过QBO.RICORTS.OWN_RIC联接表。我的难题是,在NIIN字段下,多行可以相同,但RIC的值不同。

示例:

NIIN         RIC
123455        A
122222        B
123456        C
122222        A

我想查询NIINS的不同计数,该计数由不重叠的不同服务分隔。因此示例NIIN仅应查找仅与A关联的不同值,而在B,C,D等中找不到相同的NIIN

SELECT D.SERVICE, COUNT(C.NIIN)
FROM DDS2ENVR.QBO C 
JOIN KCA0001.ORTS D ON D.OWN_RIC = C.RIC
WHERE C.SITE_ID = ('HEAA')
GROUP BY D.SERVICE
HAVING COUNT(DISTINCT C.NIIN) > 1 

如果这没有任何意义,请提出问题。

1 个答案:

答案 0 :(得分:0)

使用Not Exists

SELECT D.SERVICE, COUNT(C.NIIN)
FROM DDS2ENVR.QBO C 
JOIN KCA0001.ORTS D ON D.OWN_RIC = C.RIC
WHERE C.SITE_ID = ('HEAA')
      and NOT EXISTS (Select 1 from DDS2ENVR.QBO C1 where C1.NIIN = C.NIIN and C1.RIC <> C.RIC)
GROUP BY D.SERVICE
HAVING COUNT(DISTINCT C.NIIN) > 1 

如果表DDS2ENVR.QBO不包含重复项,并且您的dbms支持CTE

With cte as
(Select NIIN from DDS2ENVR.QBO group by NIIN having count(*) = 1)
SELECT D.SERVICE, COUNT(C.NIIN)
FROM DDS2ENVR.QBO C 
JOIN KCA0001.ORTS D ON D.OWN_RIC = C.RIC
WHERE C.SITE_ID = ('HEAA')
      and C.NIIN in (Select * from cte)    
GROUP BY D.SERVICE
HAVING COUNT(DISTINCT C.NIIN) > 1