6

我有一个包含 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

我唯一想到的就是工会。有什么想法可以在单个查询中更清洁(没有联合)?

4

3 回答 3

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 演示

于 2012-10-09T23:08:35.707 回答
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

如果要转换的列数未知,则可以使用动态 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

如果您想将数据集过滤为仅以开头的数据集,B or M则可以使用WHERE子句进行过滤。

where substring(name, 1, 1) in ('B', 'M')
于 2012-10-09T23:11:53.937 回答
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
于 2012-10-10T04:30:39.313 回答