SQL Group按自定义范围?

时间:2014-10-19 08:16:50

标签: sql sql-server select case

我有一张存储披萨订单的表格。该表有一个名为quantity的值;特定顺序的比萨饼数量。我需要“创建一个查询,根据订单中的不同披萨数量分配订单。问题说明”您的SQL查询应该计算具有以下披萨数量的订单数量:1,2,3,4,5,研究了一段时间后,我想出了这个查询,但它没有按照我想要的方式工作。这是查询及其结果。提前致谢。

SELECT CASE 
    WHEN Quantity = 1 THEN '1 ' 
    WHEN Quantity = 2 THEN '2' 
    WHEN Quantity = 3 THEN '3 ' 
    WHEN quantity = 4 THEN '4' 
    WHEN quantity = 5 THEN '5 '  
    WHEN quantity = 6 THEN '6' 
    ELSE '>6' 
    END AS Range, COUNT(Quantity) AS Amount
FROM  orders
GROUP BY Quantity

输出:

Range     Amount
1         2
2         3
3         3
4         4
5         5
6         1
>6        1
>6        2
>6        2
>6        1

我如何分组> 6范围并计算金额。所以它在一个'> 6'条目下?

3 个答案:

答案 0 :(得分:3)

一种可能的方法是对CASE WHEN子句使用相同的GROUP BY语句,例如*:

SELECT CASE 
    WHEN Quantity <= 6 THEN CAST(Quantity as VARCHAR(1))
    ELSE '>6' 
    END AS Range, COUNT(Quantity) AS Amount
FROM  orders
GROUP BY (CASE 
    WHEN Quantity <= 6 THEN CAST(Quantity as VARCHAR(1))
    ELSE '>6' 
    END)        

*)使用原始CASE WHEN语句的简化版本。用SQL Server的SQL Server风格编写。

答案 1 :(得分:1)

运行此查询而不是之前的查询:

SELECT CASE 
WHEN Quantity = 1 THEN '1 ' 
WHEN Quantity = 2 THEN '2' 
WHEN Quantity = 3 THEN '3 ' 
WHEN quantity = 4 THEN '4' 
WHEN quantity = 5 THEN '5 '  
WHEN quantity = 6 THEN '6' 
ELSE '>6' 
END AS Range, COUNT(Quantity) AS Amount
FROM  orders
GROUP BY Range

答案 2 :(得分:-1)

选择IF(数量&gt; 6,&#39;&gt;&#39;,数量)AS范围,(数量*金额)AS金额 来自订单