SQL Server 计算表的每一列中不同值的数量

编程入门 行业动态 更新时间:2024-10-10 21:32:36
本文介绍了SQL Server 计算表的每一列中不同值的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个大约 150 列的表格.我想找到每一列的 count(distinct(colName)) 但我想知道是否有办法在不实际输入每个列名的情况下这样做.

I have a table with ~150 columns. I'd like to find the count(distinct(colName)) for each column but am wondering if there's a way to do so without actually typing out each column name.

理想情况下我会使用 count(distinct(*)) 但这不起作用.

Ideally I would use count(distinct(*)) but this doesn't work.

还有其他建议吗?

如果这是我的桌子:

id col1 col2 col3 ... 01 10001 west north 02 10001 west south 03 10002 east south 04 10002 west north 05 10001 east south 06 10003 west north

我正在寻找这个输出

count(distinct(id)) count(distinct(col1)) count(distinct(col2)) count(distinct(col3)) 6 3 2 2

推荐答案

您可以这样做:

DECLARE @query varchar(max) SELECT @query = 'SELECT ' + SUBSTRING((SELECT ',' +'COUNT(DISTINCT(' + column_name + ')) As ' + column_name + ' ' FROM information_schema.columns WHERE table_name = 'table_name' for xml path('')),2,200000) + 'FROM table_name' PRINT(@query)

更多推荐

SQL Server 计算表的每一列中不同值的数量

本文发布于:2023-11-22 02:07:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615558.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数量   SQL   Server

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!