2011-03-20 17 views
1

爲了簡化,我有樹表:productsproducts-vs-ordersorders如何分組並統計在一行中?

  1. products字段: '產品ID', '姓名', 'isGratis',...
  2. products-vs-orders字段: '產品ID',「訂單ID」
  3. orders字段: '訂單ID', '標題',...

其實,我有這樣的查詢:

SELECT orders.OrderID, orders.Title, COUNT(`products`.`isGratis`) AS "Quantity", `products`.`isGratis` 
FROM `orders`, `products-vs-orders`, `products` 
WHERE `orders`.`OrderID` = `products-vs-orders`.`OrderID` AND `products-vs-orders`.`ProductID` = `products`.`ProductID` 
GROUP BY `products`.`PackID`, `products`.`isGratis` 

這個查詢工作,並返回這個需要收費的結果:

OrderID, Title,  Quantity, isGratis 
1   My Order  20   0 
1   My Order  3   1 
2   An other  8   0 
2   An other  1   1 

我怎樣才能到單獨的cols檢索產品「免費」和「支付」的計數?

OrderID, Title,  Qt Paid,  Qt Gratis 
1   My Order  20    3 
2   An other  8    1 
+0

,因爲你被products.PackID分組您的查詢不應該工作,你的選擇有orders.OrderID和orders.Title,它們都不在你的GROUP BY子句中。我認爲你複製並粘貼錯誤。 – 2011-03-20 16:08:23

回答

4

試試這個:

SELECT 
    orders.OrderID, 
    orders.Title, 
    COUNT(orders.OrderId) - SUM(`products`.`isGratis`) AS "Qt Paid", 
    SUM(`products`.`isGratis`) AS "Qt Gratis" 
WHERE `orders`.`OrderID` = `products-vs-orders`.`OrderID` 
    AND `products-vs-orders`.`ProductID` = `products`.`ProductID` 
GROUP BY `products`.`PackID` 
+0

是的,它工作正常。感謝您的幫助。 – Akarun 2011-03-20 16:12:37

0
select orderid,title,sum(if(isgratis=0,quantity,0)) as paid,sum(if(isgratis=1,quantity,0)) as gratis from ... 
1

這應該是更合適的標準的SQL:

SELECT orders.OrderID, orders.Title, 
    SUM(CASE WHEN products.isGratis THEN 0 ELSE 1 END) AS "Qt Paid", 
    SUM(CASE WHEN products.isGratis THEN 1 ELSE 0 END) AS "Qt Gratis" 
FROM orders INNER JOIN `products-vs-orders` ON (orders.OrderID = `products-vs-orders`.OrderID) 
    INNER JOIN products ON (`products-vs-orders`.ProductID = products.ProductID) 
GROUP BY orders.OrderID, orders.Title 
+0

非常感謝!您的答案可以幫助我進行其他查詢,並節省大量時間,然後+1。 – Akarun 2011-03-24 14:16:42

+0

沒有probb,@Akarun。這是CASE聲明的標準技巧,也是CASE最受歡迎的用法之一。 – 2011-03-25 00:12:04

相關問題