A,B,C,D分组中的不同E,F?

时间:2011-11-04 14:14:00

标签: sql-server-2008 tsql

我想确定在A,B,C,D分组中E,F列组合有多于1个不同值的出现。

例如,给出以下数据:

SELECT * FROM MyTable   

A          B          C          D          E          F
---------- ---------- ---------- ---------- ---------- ----------
1          1          1          1          A          B         
1          1          1          1          A          B         
1          1          1          2          A          C         
1          1          1          2          A          D  

我想返回

A          B          C          D          
---------- ---------- ---------- ----------     
1          1          1          2         

..因为在(A,B,C,D)分组中存在多个不同的(E,F)组合。

这是用来创建测试用例的SQL!

CREATE TABLE [dbo].[MyTable](
    [A] [nchar](10) NULL,
    [B] [nchar](10) NULL,
    [C] [nchar](10) NULL,
    [D] [nchar](10) NULL,
    [E] [nchar](10) NULL,
    [F] [nchar](10) NULL
) ON [PRIMARY]

GO
INSERT INTO [dbo].[MyTable]([A], [B], [C], [D], [E], [F])
SELECT N'1         ', N'1         ', N'1         ', N'1         ', N'A         ', N'B         ' UNION ALL
SELECT N'1         ', N'1         ', N'1         ', N'1         ', N'A         ', N'B         ' UNION ALL
SELECT N'1         ', N'1         ', N'1         ', N'2         ', N'A         ', N'C         ' UNION ALL
SELECT N'1         ', N'1         ', N'1         ', N'2         ', N'A         ', N'D         '

2 个答案:

答案 0 :(得分:2)

SELECT
    A,B,C,D
FROM
    (
    SELECT
        A,B,C,D,
        ROW_NUMBER() OVER (PARTITION BY A,B,C,D,E,F ORDER BY (SELECT 1)) AS DistinctTuplesLong,
        ROW_NUMBER() OVER (PARTITION BY A,B,C,D ORDER BY (SELECT 1)) AS DistinctTuples
    FROM
        Mytable
    ) T
WHERE 
    DistinctTuplesLong < DistinctTuples

编辑:使用了错误的窗口函数

编辑2:现在使用示例数据更清晰

答案 1 :(得分:1)

SELECT A,B,C,D
FROM [dbo].[MyTable]
GROUP BY A,B,C,D
HAVING COUNT(DISTINCT E) > 1 OR COUNT(DISTINCT F) > 1

或者

WITH T
     AS (SELECT *,
                DENSE_RANK() OVER (PARTITION BY A, B, C, D ORDER BY E, F) Rnk
         FROM   [dbo].[MyTable])
SELECT DISTINCT A,
                B,
                C,
                D
FROM   T
WHERE  Rnk = 2