使用SQL Server 2008计算列中存在的组数

时间:2014-09-10 13:26:28

标签: sql sql-server sql-server-2008

我有一张如下表所示的表格:

create table test
(
  cola varchar(10) 
)

插入一些数据:

insert into test values('a');
insert into test values('a');
insert into test values('a');
insert into test values('b');
insert into test values('b');
insert into test values('c');
insert into test values('d');
insert into test values('d');

我想显示列cola

中有多少组

预期结果:

TotalGroups   a    b    c    d 
--------------------------------
 4            3    2    1    2

2 个答案:

答案 0 :(得分:3)

试试这个,删除[和]以避免sql注入:

DECLARE @sql varchar(max) = 
       'SELECT (select count(distinct cola) from test) TotalGroups'

SELECT @sql += ',' +cast(count(*) as varchar(10)) + 
      '['+ replace(replace(cola, ']', ''), '[', '') + ']'
FROM TEST
GROUP BY cola
ORDER BY cola


EXEC(@sql)

结果:

Total_Groups  a  b  c  d
4             3  2  1  2

答案 1 :(得分:1)

试试这个: -

SELECT count(distinct cola) AS Total_Groups, COUNT(CASE WHEN COLA = 'a' THEN 1 END) AS a,
                                             COUNT(CASE WHEN COLA = 'b' THEN 1 END) AS b,
                                             COUNT(CASE WHEN COLA = 'c' THEN 1 END) AS c,
                                             COUNT(CASE WHEN COLA = 'd' THEN 1 END) AS d                   
FROM TEST;

这是小提琴

http://sqlfiddle.com/#!2/fe5be/19