如何从我的数据库中选择所有非唯一列?

时间:2016-03-23 10:00:53

标签: sql-server tsql sql-server-2014 having information-schema

我使用AdventureWorks2014中的常见Microsoft SQL Server 2014示例数据库来学习SQL。

我今天刚刚了解了HAVINGInformation Schema,并尝试将两者结合起来。

原因是,我真的很想快速分辨所有表中的哪些列是共享的。这有效:

SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
ORDER BY COLUMN_NAME, TABLE_SCHEMA

但是......输出给了我独特的列名,只会减慢我的速度。

我尝试过应用"How to select non 'unique' rows"(5-7个其他SOF页面中的答案!)的答案,例如:

SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
GROUP BY COLUMN_NAME
HAVING COUNT(COLUMN_NAME) > 1

...但是我收到了这个错误:

  

Msg 8120,Level 16,State 1,Line 1 Column   ' information_schema.columns.TABLE_SCHEMA'在选择中无效   list,因为它不包含在聚合函数中   GROUP BY子句。

2 个答案:

答案 0 :(得分:1)

您可以使用查询来检索共享的所有列,然后连接到原始表以获取所有信息(模式,名称):

SELECT t.TABLE_SCHEMA,
       t.table_name,
       t.column_name
FROM INFORMATION_SCHEMA.COLUMNS t
INNER JOIN (
    SELECT s.column_name
    FROM INFORMATION_SCHEMA.COLUMNS s
    GROUP BY s.column_name
    HAVING COUNT(s.column_name) > 1
) tt ON (t.column_name = tt.column_name)

答案 1 :(得分:0)

SELECT *
FROM (
    SELECT
        col = c.name,
        obj_name = o.name,
        sch_name = SCHEMA_NAME(o.[schema_id]),
        col_type = TYPE_NAME(c.system_type_id),
        RowNum = COUNT(1) OVER (PARTITION BY c.name, o.[type] ORDER BY 1/0)
    FROM sys.columns c
    JOIN sys.objects o ON c.[object_id] = o.[object_id]
    WHERE o.[type] = 'U'
) t
WHERE t.RowNum > 1
ORDER BY t.col

输出:

col                     obj_name            sch_name  col_type    
----------------------- ------------------- --------- ------------
dbid                    spt_fallback_usg    dbo       smallint    
dbid                    spt_fallback_db     dbo       smallint       
xserver_name            spt_fallback_usg    dbo       varchar     
xserver_name            spt_fallback_db     dbo       varchar     
xserver_name            spt_fallback_dev    dbo       varchar