2013-08-29 26 views
3

我有一個表(SQL 2008)A,B,C,d,在COL1 ë值是否有一種方式來獲得由COL1分組,返回的結果將是數組通過與SQL結合值

A - # 
B - # 
other - # 

謝謝

+0

你給了什麼試試嗎?你嘗試了什麼?結果是什麼? – BWS

回答

5
select 
    case when col1 in ('a','b') then col1 else 'other' end, 
    count(*) 
from tab 
group by case when col1 in ('a','b') then col1 else 'other' end 
+0

謝謝!這是我正在尋找的 – chibis

0
SELECT col1, COUNT(col1) 
FROM mytable 
WHERE col1 IN ('A', 'B') 
GROUP BY col1 
UNION 
SELECT col1, COUNT(col1) 
FROM mytable 
WHERE col1 IS NULL OR col1 NOT IN ('A','B') 
GROUP BY col1 
ORDER BY col1 
0
SELECT CASE col1 
WHEN a then 'nameofnewcolumn' 
WHEN b then 'nameofnewcolumn' 
ELSE 'other' 
END 
FROM TABLE 

這應該組中的所有值列或不適合的另一組的其他組的一切。

0

試試這個:

SELECT ColumnName, COUNT(ColumnName) 
    FROM NyTable 
    GROUP BY ColumnName 
6

重複的CASE表達的作品,但我覺得它不那麼乏味只有一次執行表達。計劃是相同的。

;WITH x AS 
(
    SELECT Name = CASE WHEN Name IN ('A','B') THEN Name 
    ELSE 'Other' END 
    FROM dbo.YourTable 
) 
SELECT Name, COUNT(*) FROM x 
GROUP BY Name; 

如果排序是非常重要的(如Other應該在結果中的最後一行,即使其他的名字來後,按字母順序),那麼你可以說:

ORDER BY CASE WHEN Name = 'Other' THEN 1 ELSE 0 END, Name; 
1
SELECT res.col1, COUNT(*) 
FROM 
     (SELECT 
     (CASE col1 WHEN 'A' THEN 'A' 
       WHEN 'B' THEN 'B' 
       ELSE 'other' 
     END) as col1 
     FROM table) as res 
GROUP BY col1 

test

0

如果'other'應該是最後一行,'A','B'實際上可以是任意的(例如'李子','zillion'),可以使用以下內容:

;with cte as (
    select 
     col1 = case when t.col1 in ('A', 'B') then t.Col1 else 'other' end, 
     ordnum = case when t.col1 in ('A', 'B') then 0 else 1 end 
    from TableName 
) 
select col1, count(1) 
from cte 
group by col1 
order by ordnum, col1