group by in sql组合值

时间:2013-08-29 19:06:39

标签: sql sql-server-2008

我有一个表(sql 2008),其中包含col1中的A,B,C,D,E值 有没有办法获得按col1分组的计数,以便返回的结果为

A - #
B - #
other - #

谢谢

7 个答案:

答案 0 :(得分: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 :(得分: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

答案 2 :(得分: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

答案 3 :(得分: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

答案 4 :(得分:0)

SELECT CASE col1
WHEN a then 'nameofnewcolumn'
WHEN b then 'nameofnewcolumn'
ELSE 'other'
END
FROM TABLE

这应该将所有值分组到列中,else分组不适合OTHER组的所有内容。

答案 5 :(得分:0)

试试这个:

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

答案 6 :(得分:0)

如果'other'应该是最后一行,'A','B'实际上可以是任意的(例如'plums','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