爲了簡化,我有樹表:products
,products-vs-orders
,orders
如何分組並統計在一行中?
products
字段: '產品ID', '姓名', 'isGratis',...products-vs-orders
字段: '產品ID',「訂單ID」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
,因爲你被products.PackID分組您的查詢不應該工作,你的選擇有orders.OrderID和orders.Title,它們都不在你的GROUP BY子句中。我認爲你複製並粘貼錯誤。 – 2011-03-20 16:08:23