查找计数发生次数

时间:2012-10-09 23:01:35

标签: sql sql-server tsql pivot

我有一个包含2列的表(db:sql server 2008):

id         name
-----      ------
1          Bob
2          Mike
3          Mary
4          Mike
5          Barry
6          Benson
7          Burrows

我想得到一个以B开头并以M开头的名字(一行)?

像:

Count of B        Count of M
-----------      ------------
4                  3

唯一能给我的是工会。任何想法在单个查询中更清洁(没有联合)?

3 个答案:

答案 0 :(得分:4)

使用CASE

尝试
SELECT  SUM(CASE WHEN SUBSTRING(name,1,1) = 'B' Then 1 ELSE 0 END),
        SUM(CASE WHEN SUBSTRING(name,1,1) = 'M' Then 1 ELSE 0 END)
FROM TAbleName

SQLFiddle Demo

答案 1 :(得分:4)

您可以使用PIVOT。如果您有已知数量的列,则可以使用STATIC PIVOT:

对值进行硬编码
select *
from
(
  select substring(name, 1, 1) name, -- use the same field twice, 
    substring(name, 1, 1) initial    -- once will be for the count the other for columns
  from yourtable
) x
pivot
(
  count(name)
  for initial in ([B], [M])
) p

请参阅SQL Fiddle With Demo

如果要转换的列数未知,则可以使用动态sql并创建动态PIVOT:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' 
                      + QUOTENAME(substring(name, 1, 1)) 
                    from yourtable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT ' + @cols + ' from 
             (
              select substring(name, 1, 1) name, 
                substring(name, 1, 1) initial
              from yourtable
            ) x
            pivot 
            (
                count(name)
                for initial in (' + @cols + ')
            ) p '

execute(@query)

请参阅SQL Fiddle with Demo

如果您希望将数据集过滤到仅以B or M开头的数据集,那么您可以使用WHERE子句进行过滤。

where substring(name, 1, 1) in ('B', 'M')

答案 2 :(得分:1)

这是另一种方式

Declare @T Table ([id] varchar(5), [name] varchar(7));

INSERT INTO @T([id], [name])
VALUES
    ('1', 'Bob'),
    ('2', 'Mike'),
    ('3', 'Mary'),
    ('4', 'Mike'),
    ('5', 'Barry'),
    ('6', 'Benson'),
    ('7', 'Burrows')

;WITH CTE AS
(SELECT
    Initials = SUBSTRING(name,1,1)
    ,Cnt = COUNT([name]) 
FROM @t 
GROUP BY SUBSTRING(name,1,1))

SELECT 
    [Count of B] = (SELECT Cnt FROM CTE WHERE Initials = 'B')
    ,[Count of M] = (SELECT Cnt FROM CTE WHERE Initials = 'M')

<强>结果

Count of B  Count of M
4             3