我需要一个SQL查询来比较列值与同一个表中的行

时间:2014-05-16 02:36:09

标签: sql

我有一张名为BB_BOATBKG的表格,其中包含Z_IDBK_KEYPAXSUM列的乘客旅行详情:

Z_ID = BookingNumber* LegNumber
BK_KEY = BookingNumber
PAXSUM = Total number passengers travelled in each leg for a particular booking

例如:

Z_ID         BK_KEY     PAXSUM
001234*01   001234           2
001234*02   001234           3
001287*01   001287           5
001287*02   001287           5
002323*01   002323           7
002323*02   002323           6

我想从BK_KEY获取所有预订号码BB_BOATBKG的列表,其中同一预订的每条腿的乘客总数PAXSUM不同 例如,对于预订号AA*Leg01可能有2名乘客,A* Leg02可能有3名乘客

2 个答案:

答案 0 :(得分:2)

依赖于您的RDBM,可能有多种选择可用。最适用的解决方案是:

SELECT A.Z_ID, A.BK_KEY, A.PAXSUM
FROM BB_BOATBKG A
JOIN ( 
    SELECT BK_KEY
    FBB_BOATBKGROM BB_BBK_KEY
    GROUP BY BK_KEY
    HAVING COUNT( DISTINCT PAXSUM ) > 1
) B
    ON A.BK_KEY = B.BK_KEY

如果您的DBMS支持OLAP功能,请查看RANK() OVER (...)

答案 1 :(得分:1)

这有点违反直觉,但您可以在{BK_KEY,PAXSUM}上将表连接到自身,并仅提取连接结果为空的记录。

我认为这样做:

SELECT
    a.BK_KEY
FROM
    BB_BOATBKG a
    LEFT OUTER JOIN BB_BOATBKG b ON a.BK_KEY = b.BK_KEY AND a.PAXSUM = b.PAXSUM
WHERE
    b.Z_ID IS NULL
GROUP BY
    a.BK_KEY

编辑:我想我错过了一些无关紧要的事情。我认为你可以通过一些非常讨厌的次级选择来做到这一点,la:

SELECT
    b.BK_KEY
FROM
    (
        SELECT
            a.BK_KEY,
            Count = COUNT(*)
        FROM
            (
                SELECT
                    a.BK_KEY,
                    a.PAXSUM
                FROM
                    BB_BOATBKG a
                GROUP BY
                    a.BK_KEY,
                    a.PAXSUM
                HAVING
                    COUNT(*) = 1
            ) a
        GROUP BY
            a.BK_KEY
    ) b
    INNER JOIN
    (
        SELECT
            c.BK_KEY,
            Count = COUNT(*)
        FROM
            BB_BOATBKG c
        GROUP BY
            c.BK_KEY
    ) c ON b.BK_KEY = c.BK_KEY AND b.Count = c.Count