T-SQL:跨多列计数和分组

时间:2012-10-06 02:37:38

标签: sql tsql sql-server-2005

我有下表:

Name | Col1 | Col2 | Col3
John   A      B      C
John   A      D      A
Bill   A      A      D
Bill   F      A      A
Steve  F      A      B
Steve  C      C      A

我想知道John,Bill和Steve有多少人......

e.g。约翰:3,比尔:4,史蒂夫:2

我怎么能用T-SQL做到这一点?感谢。

3 个答案:

答案 0 :(得分:5)

您可以使用UNPIVOT功能:

select name, count(val) TotalAs
from yourtable
unpivot
(
  val
  for col in (col1, col2, col3)
) u
where val = 'A'
group by name

请参阅SQL Fiddle with Demo

答案 1 :(得分:2)

试试这个SQL Fiddle For below

declare @table table (name varchar(10), c1 char(1), c2 char(1), c3 char(1))
insert into @table
SELECT 'John','A','B','C' UNION
SELECT 'John','A','D','A' UNION
SELECT 'Bill','A','A','D' UNION
SELECT 'Bill','F','A','A' UNION
SELECT 'Steve','F','A','B' UNION
SELECT 'Steve','C','C','A' 

; WITH CTE AS 
(
   SELECT name, 
       (SELECT Count(CASE WHEN val = 'A' Then 1 ELse Null end) 
        FROM (VALUES (c1),(c2),(c3)) AS value(val)) As ACOL
   from @table
)

SELECT Name, SUM(ACOL) ACount FROM CTE GROUP BY NAME

答案 2 :(得分:0)

对于SQL Server 2012,这个怎么样?它可能会更快。

select name,sum(datalength(concat(col1,col2,col3))-
                datalength(replace(concat(col1,col2,col3),'A','')))
from yourtable
group by name;