SQL Server - 选择一列匹配但另一列不匹配的行

时间:2016-05-26 19:53:59

标签: sql-server

我需要为相同的列名选择数据类型不同的行。

这是我的数据集。预计会突出显示行。

dataset

我尝试了以下SQL脚本,但它没有返回预期的结果

SELECT COLUMN_NAME, DATA_TYPE
FROM tablecolumns
WHERE COLUMN_NAME IN (
    SELECT COLUMN_NAME
    FROM tablecolumns
    WHERE COLUMN_NAME IN (
        SELECT COLUMN_NAME
        FROM tablecolumns
        GROUP BY DATA_TYPE, COLUMN_NAME
        HAVING count(*) = 1)
    GROUP BY COLUMN_NAME
    HAVING count(*) > 1)
ORDER BY COLUMN_NAME

以下是SQL小提琴http://sqlfiddle.com/#!3/6e9665/1

的链接

2 个答案:

答案 0 :(得分:2)

首先,您可以使用GROUP BY和HAVING获取具有多个数据类型的列名:

SELECT COLUMN_NAME
FROM tablecolumns
GROUP BY COLUMN_NAME
HAVING count(DISTINCT DATA_TYPE) > 1

然后,您可以使用WHERE IN(..)

显示其列名称在该结果中的所有行
SELECT COLUMN_NAME, DATA_TYPE
FROM tablecolumns
WHERE COLUMN_NAME IN (
   SELECT COLUMN_NAME
   FROM tablecolumns
   Group by COLUMN_NAME
   HAVING count(DISTINCT DATA_TYPE) > 1
)
ORDER BY COLUMN_NAME

或使用INNER JOIN

SELECT a.COLUMN_NAME , a.DATA_TYPE
FROM tablecolumns a
INNER JOIN (
   SELECT b.COLUMN_NAME
   FROM tablecolumns b
   Group by b.COLUMN_NAME
   HAVING count(DISTINCT b.DATA_TYPE) > 1
) c ON c.COLUMN_NAME = a.COLUMN_NAME
ORDER BY a.COLUMN_NAME

答案 1 :(得分:0)

如果你有SQL Server 2008或更高版本,你可以使用COUNT()窗口函数来实现你想要的:

WITH CTE_DistinctColumnsAndTypes
AS
(
    SELECT   COLUMN_NAME
            ,DATA_TYPE
    FROM    tablecolumns
    GROUP BY COLUMN_NAME, DATA_TYPE
),
CTE_ColumnsAndTypeCount
AS
(
    SELECT  COLUMN_NAME
            ,DATA_TYPE
            ,COUNT(DATA_TYPE) OVER (PARTITION BY COLUMN_NAME) AS TypeCount
    FROM CTE_DistinctColumnsAndTypes
)
SELECT  COLUMN_NAME
        ,DATA_TYPE
FROM    CTE_ColumnsAndTypeCount
WHERE   TypeCount > 1