T-SQL列值计数

时间:2012-01-31 19:37:17

标签: tsql

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


    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


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


     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


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

由于

4 个答案:

答案 0 :(得分:4)

你可以尝试:

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
...

您需要为要汇总的每个列为SELECT写一个额外的UNION,但它会返回您所追求的数据。

答案 1 :(得分:1)

您是否可以使用GROUP BY

为每个所需列执行单独查询
SELECT Column1, COUNT(Column1) FROM TableName
GROUP BY Column1

答案 2 :(得分:1)

工会方法将为您提供最好的服务。每个联合的单个查询看起来像这样:

Select Distinct Column1, COUNT(Column1)OVER(PARTITION BY Column1) Col1Count, 'Column1' ColumnName
From ColTable
Union All
...

答案 3 :(得分:1)

您可以在外部查询中的派生表(或CTE)和group by列名称和值中使用unpivot

试试这个:

declare @T table
(
  ID int,
  Column1 char(1), 
  Column2 char(1), 
  Column3 char(1),
  Column4 char(1),
  Column5 char(1)
)

insert into @T values
(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')

;with C as
(
  select ID, Col, Val
  from (
         select ID, Column1, Column2, Column3, Column4, Column5
         from @T
       ) as T
  unpivot (Val for Col in (Column1, Column2, Column3, Column4, Column5)) as U   
)
select Col, Val, count(*) as ValCount
from C
group by Col, Val
order by Col