2014-10-08 45 views
0

我有我所screenshotted並上傳此圖片的表:編寫特定的SQL集團By語句

enter image description here

我需要創建一個SQL查詢,計算的訂單數量與以下比薩餅數量:1,2,3,4,5,6和以上6.

我試過一些SQL語句,但沒有找到正確的。

我現在的嘗試是

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
      ConnectionString="<%$ ConnectionStrings:ConnectPizza %>" 
      SelectCommand="Select '1' AS Caption, Count(quantity) AS Count FROM orders WHERE quantity = 1 
      UNION ALL 
      Select '2' AS Caption, Count(quantity) AS Count FROM orders WHERE quantity = 2 
      UNION ALL 
      Select '3' AS Caption, Count(quantity) AS Count FROM orders WHERE quantity = 3 
      UNION ALL 
      Select '4' AS Caption, Count(quantity) AS Count FROM orders WHERE quantity = 4 
      UNION ALL 
      Select '5' AS Caption, Count(quantity) AS Count FROM orders WHERE quantity = 5 
      UNION ALL 
      Select '6' AS Caption, Count(quantity) AS Count FROM orders WHERE quantity = 6 
      UNION ALL 
      Select 'Above 7' AS Caption, Count(quantity) AS Count FROM orders WHERE quantity > 7"> 
     </asp:SqlDataSource> 

,但它是不會成功的。

我也想做一個圖表,但即使我的sql語句成功了,我也不確定我會爲我的X和Y值成員輸入什麼內容。

任何幫助,將不勝感激。

+2

你期望輸出什麼? – Arion 2014-10-08 06:55:45

+0

又一個**非ASP經典**問題,'' Lankymart 2014-10-08 07:56:02

回答

0

這會按照您想要的方式打出您的數量,然後將數量計爲1-7。我沒有在組中使用這種情況,因爲它在許多數據庫中都是不允許的。

Select o.quantity AS Caption, Count(o.quantity) AS Count 
FROM (SELECT CASE WHEN quantity < 7 THEN Quantity ELSE 7 END) quantity from orders) o 
group by o.quantity 
+3

更好,如果你進一步解釋 – nobalG 2014-10-08 07:14:19

0

這應該讓你關閉,但會標註全部7+量爲「7」

select case when quantity < 7 then quantity else 7 end, 
     count(*) 
from orders 
group by case when quantity < 7 then quantity else 7 end 

爲了得到7+標註正確,需要確切地知道你是哪個SQL變種使用