SELECT column_name, STRING_AGG(table_name, ', ') AS tables, COUNT(*) AS count
FROM information_schema.columns
GROUP BY column_name
ORDER BY COUNT(*) DESC
select distinct A.COLUMN_NAME,
STUFF((SELECT distinct ', ' + B.TABLE_NAME
from INFORMATION_SCHEMA.COLUMNS B
where A.COLUMN_NAME = B.COLUMN_NAME
FOR XML PATH(''), TYPE
).value('.', 'VARCHAR(MAX)')
,1,2,'') AS [TABLE_NAMES]
, X.COUNT
from INFORMATION_SCHEMA.COLUMNS A
LEFT JOIN
(
select COLUMN_NAME, COUNT(1) [COUNT]
from INFORMATION_SCHEMA.COLUMNS
GROUP BY COLUMN_NAME
) X ON X.COLUMN_NAME = A.COLUMN_NAME
ORDER BY X.COUNT DESC
2条答案
按热度按时间disbfnqx1#
1.作为数据源,您可以使用INFORMATION_SCHEMA.COLUMNS,也可以连接sys.Columns和sys.ables。
1.要只获取表数,
COUNT(*)
和GROUP BY
就足够了。1.要获取逗号分隔表的列表,请在SQL Server 2017或更高版本中使用STRING_AGG。如果您使用的是较旧版本的SQL Server,可以在以下相关问题中找到解决方法:
SQL group_concat function in SQL Server
上述所有合计收益率(fiddle):
xpszyzbs2#
解决方案:
谢谢大家!:)