用group by计算sql

时间:2014-10-08 05:04:14

标签: sql sql-server tsql

表名:mytable

Id  username  pizza-id  pizza-size  Quantity  order-time
--------------------------------------------------------------
1    xyz         2        9          2        09:00 10/08/2014
2    abc         1        11         3        17:45 13/07/2014

这是mytable,有6列。 Idintusernamevarcharorder-timedatetime,其余为integer数据类型。

如何计算以下披萨数量的订单数量:1,2,3,4,5,6,7及以上7?

使用T-SQL查询。

如果有人帮我找到解决方案,那将非常有帮助。

3 个答案:

答案 0 :(得分:1)

尝试

Select CASE WHEN Quantity > 7 THEN 'OVER7' ELSE Cast(quantity as varchar) END Quantity, 
COUNT(ID) NoofOrders 
from mytable
GROUP BY CASE WHEN Quantity > 7 THEN 'OVER7' ELSE Cast(quantity as varchar) END

Select

SUM(Case when Quantity = 1  then 1 else 0 end) Orders1,
SUM(Case when Quantity = 2  then 1 else 0 end) Orders2,
SUM(Case when Quantity = 3  then 1 else 0 end) Orders3,
SUM(Case when Quantity = 4  then 1 else 0 end) Orders4,
SUM(Case when Quantity = 5  then 1 else 0 end) Orders5,
SUM(Case when Quantity = 6  then 1 else 0 end) Orders6,
SUM(Case when Quantity = 7  then 1 else 0 end) Orders7,
SUM(Case when Quantity > 7  then 1 else 0 end) OrdersAbove7

from mytable

答案 1 :(得分:1)

试试这个!

SELECT COUNT(ID),CASE WHEN QUANTITY<7 THEN QUANTITY ELSE 'ABOVE7' END AS QUANTITIES 
FROM mytable
GROUP BY CASE WHEN QUANTITY<7 THEN QUANTITY ELSE 'ABOVE7' END 

答案 2 :(得分:0)

如果要求就像计算具有不同披萨数量的订单数量并代表订单数量:1,2,3,4,5,6,7并考虑新类别中的所有上述订单数量:&#39 ; 7&#39;然后你可以使用窗口函数:

select case when totalorders < = 7 then cast(totalorders as varchar(10)) 
else 'Above 7' end as totalorders
, Quantity 
from 
(
    select distinct count(*) over (partition by Quantity order by Quantity asc) 
    as totalorders,
    Quantity
    from mytable   
) T
order by Quantity

DEMO

编辑:如果要求就像计算披萨数量的订单数量:1,2,3,4,5,6,7并考虑新类别中的所有其他披萨数量:&#39; 7&#39以上;然后你可以写成:

select distinct
count(*) over (
               partition by Quantity order by Quantity asc
              ) as totalorders,
Quantity
from (    
select 
case when Quantity < = 7 then cast(Quantity as varchar(20)) 
else 'Above 7' end as Quantity, id
from mytable   ) T
order by Quantity

DEMO