SQL指令显示另一个表中是否有值

时间:2018-10-16 13:05:39

标签: sql ibm-midrange db2-400

我有两个文件,标题和详细信息。在详细信息文件中,有一个关键字段来查找或加入标题。我需要计算具有详细记录的标题行的数量。我只想知道带有field1 = 'A'的记录数,以及带有field1 = 'A'= 'B'的记录的标题行数。

它不适用于Join或CASEsubselect查询。

这是一个简化的示例:

  • 表AA(标题)和表BB(详细信息)。表AA具有字段HeadId
  • 表BB具有三个字段:HeadIdDetIdData。 HeadId用于与标题表联接。字段数据的值可以等于A或B。AA行在BB上可以有更多行。

我需要知道AA中有几行具有BB的只有Data = A值的行,有几行具有A和B的两行。我只需要执行一个SQL查询即可。

请你能帮我吗?

2 个答案:

答案 0 :(得分:0)

我为此使用了联合,并且仅使用了“ BB”表进行计数

SELECT COUNT(*) as count, 'Only A' as type
FROM BB b
WHERE NOT EXISTS (SELECT headId FROM BB WHERE Data != 'A' AND headId = b.headId)
GROUP BY headId, data
UNION
SELECT COUNT(*), 'A and B'
FROM BB b1
JOIN BB b2 ON b1.headId = b2.headId AND b1.id != b2.id AND b1.data != b2.data
WHERE b1.data IN ('A', 'B') AND b2.data IN ('A', 'B')
GROUP BY b1.headId

答案 1 :(得分:0)

有多种方法可以完成同一件事。将我的代码基于Joakim的回答,此代码对我有用:

SELECT headId 
  FROM HEADER;

HEADID
------
     1
     2
     3
     4

select headId,
       detailId,
       someData
  from Detail
;

HEADID     DETAILID  SOMEDATA
------  -----------  --------
     1            1  A       
     2            1  A       
     2            2  B       
     3            1  X       
     4            1  A       

SELECT 'Only A' AS TYPE,
        COUNT(*) AS COUNT
  FROM HEADER H
 WHERE EXISTS (SELECT 1 FROM DETAIL D
               WHERE D.HEADID = H.HEADID AND SOMEDATA = 'A')
   AND NOT EXISTS (SELECT 1 FROM DETAIL D
                   WHERE D.HEADID = H.HEADID AND SOMEDATA <> 'A')
 GROUP BY 'Only A'
UNION
SELECT 'Both A and B' AS TYPE,
        COUNT(*) AS COUNT
  FROM HEADER H
 WHERE EXISTS (SELECT 1 FROM DETAIL D
               WHERE D.HEADID = H.HEADID AND SOMEDATA = 'A')
   AND EXISTS (SELECT 1 FROM DETAIL D
                WHERE D.HEADID = H.HEADID AND SOMEDATA = 'B') 
 GROUP BY 'Both A and B'
;

TYPE                COUNT
------------  -----------
Both A and B            1
Only A                  2

希望有帮助!