2014-10-08 63 views
0

表名:mytable計數與組SQL由

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列。 Idint,usernamevarchar,order-timedatetime而其餘的是integer數據類型。

如何計算具有下列比薩餅數量的訂單數量:1,2,3,4,5,6,7及以上7?

使用T-SQL查詢。

這將是非常有益的如果任何人可以幫助我找到解決方案。

+0

你的問題還不清楚。請提供你正在尋找 – Wanderer 2014-10-08 05:11:42

回答

0

如果要求像計數具有不同數量的比薩餅的訂單數量,表示訂單的計數爲:1,2,3,4,5,6,7和考慮所有上述在新的類別順序計數: '高於7',那麼就可以使用窗口函數爲:

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並考慮一個LL等比薩餅的數量在新的類別:「以上7」,那麼你可以寫爲:

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

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 
+0

樣本結果是我們確定OP想要1行而不是8?也許一個完整的答案將包括兩個(例如'GROUP BY CASE WHEN Quantity> 7 THEN'OVER7'ELSE Cast(quantity as varchar)END' – 2014-10-08 05:18:26

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