2012-10-09 71 views
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 

,對我出現的唯一事情是工會。任何想法在一個單一的查詢(無工會)乾淨呢?

+0

我不知道工會是如何讓你的兩列 – Paparazzi

回答

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

+0

也許增加一個子字符串(姓名,1 ,1)in('B','M') – Paparazzi

+1

謝謝,效果很棒! –

4

您可以使用PIVOT這一點。如果你有一個著名的列數,那麼你可以硬編碼一個靜態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') 
+0

擊敗我 – RThomas

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