我有这个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
中的各个记录列表?例如,我知道FPBTEN12245
中有2条记录,但是如何获得列出的2条记录的信息列表以及其他记录的信息?
FPBBLD33567 125826 2
答案 0 :(得分: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;
我还建议使用作为表格缩写的别名,而不是任意字母。这种做法使查询更易于阅读和维护。
答案 1 :(得分: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