T-SQL 列值计数 [英] T-SQL Column values count

查看:45
本文介绍了T-SQL 列值计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个表 A,它有 5 列(Column1、Column2 .. Column5),每列中的值是一个字符大小并且仅存储按字母顺序如下

<前>ID 列 1 列 2 列 3 列 4 列 51 A C D A B2 A D A B A3 B K Q C Q4 A K E B5 F K F F S

我需要对存储在 column1 到 column5 中的每个不同值进行计数,我想要以下信息

<前>Column1 有 A 的计数 = 3,B 的计数 = 1,F 的计数 = 1Column2 有 C 的计数=1,D 的计数=1,K 的计数=3等等

返回这些值的正确方式和格式是什么?

谢谢

解决方案

你可以试试:

SELECT 'Col1' 为 'Col',Column1 为 'Value',COUNT(*) 为 'Ct'从我的表按列 1 分组联合所有SELECT 'Col2', Column2, COUNT(*)从我的表按第 2 列分组...

对于要聚合的每一列,您需要为 UNION 编写一个额外的 SELECT,但它会返回您想要的数据.

Say I have a table A and it has 5 columns (Column1, Column2.. Column5), the values in each column is one char size and stored only as alphabetic as follows


    ID Column1 Column2 Column3 Column4 Column5
    1   A        C       D        A      B
    2   A        D       A        B      A
    3   B        K       Q        C      Q
    4   A        K       E        E      B
    5   F        K       F        F      S


I need a count of each different value stored in column1 to column5, I want the following information


     Column1 has A's count=3, B's count=1, F's count=1
     Column2 has C's count=1, D's count=1, K's count=3

     and so on


What is the correct way and format to return these values?

Thanks

解决方案

You could try:

SELECT 'Col1' As 'Col', Column1 as 'Value', COUNT(*) as 'Ct'
FROM MyTable
GROUP BY Column1
UNION ALL
SELECT 'Col2', Column2, COUNT(*)
FROM MyTable
GROUP BY Column2
...

You will need to write an additional SELECT to UNION for each column you want to aggregate, but it will return the data you are after.

这篇关于T-SQL 列值计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆