0

我有这个 SQL 脚本:

SELECT distinct 
    A.APNO, B.APUSEINSPKEY, Count(*)
FROM  
    CDR_USE.useappl A, CDR_USE.USEINSP B, 
    CDR_USE.useappldetail C, FIREUSEPERMITS.buildinginfo D, 
    FIREUSEPERMITS.blginfogrd E
WHERE 
    A.APUSEKEY = B.APUSEKEY
    AND a.apusekey = b.apusekey
    AND A.apusekey = C.APUSEKEY
    AND c.apuseappldtlkey = d.apuseappldtlkey
    AND d.buildinginfokey = E.BUILDINGINFOKEY
    AND E.EXPIREDATE IS NULL
GROUP BY 
    A.APNO, B.APUSEINSPKEY
HAVING 
    COUNT(*) > 1 

返回此结果:

*APNO          APUSEINSPKEY  COUNT
*FPBTEN12245     28922        2
*FPBBLD17053     52096        2
*FPBTEN22105     74489        2
*FPBTEN22126     74552        2
*FPBTEN25730     91536        2

我需要什么代码来获取每个记录的列表APNO?例如,我知道 中有 2 条记录FPBTEN12245,但我如何获取列出的这 2 条记录的信息列表以及其余记录的信息?

FPBBLD33567 125826  2
4

2 回答 2

0

首先,您应该使用标准join语法。其次,大多数数据库都支持窗口函数,因此您可以使用它们获得所有基本结果:

select *
from (SELECT A.*,
             Count(*) over (partition by A.APNO, B.APUSEINSPKEY) as cnt
      FROM  CDR_USE.useappl A join
            CDR_USE.USEINSP B
            on A.APUSEKEY = B.APUSEKEY join
            CDR_USE.useappldetail C
            on A.apusekey = C.APUSEKEY join
            FIREUSEPERMITS.buildinginfo D
            on c.apuseappldtlkey = d.apuseappldtlkey join
            FIREUSEPERMITS.blginfogrd E
            on d.buildinginfokey = E.BUILDINGINFOKEY
      WHERE E.EXPIREDATE IS NULL
     ) t
where cnt > 1;

我还建议使用作为表格缩写的别名,而不是任意字母。这种做法使查询更易于阅读和维护。

于 2013-10-29T15:34:48.440 回答
0

我无法测试我发布的代码,但我相信它应该可以工作

SELECT distinct A.APNO, B.APUSEINSPKEY 
FROM  
    CDR_USE.useappl A, 
    CDR_USE.USEINSP B, 
    CDR_USE.useappldetail C, 
    FIREUSEPERMITS.buildinginfo D, 
    FIREUSEPERMITS.blginfogrd E
WHERE A.APUSEKEY = B.APUSEKEY
  AND B.apusekey = C.APUSEKEY
  AND C.apuseappldtlkey = D.apuseappldtlkey
  AND D.buildinginfokey = E.BUILDINGINFOKEY
  AND E.EXPIREDATE IS NULL
  AND (SELECT COUNT(1) 
       FROM CDR_USE.useappl A2,
            CDR_USE.USEINSP B2 
       WHERE A2.APUSEKEY = B2.APUSEKEY
         AND B2.APUSEKEY=A.APUSEKEY
       ) >  1
于 2013-10-29T15:46:52.660 回答