如何分组和统计?

时间:2011-03-20 15:59:06

标签: mysql sql count group-by

为了简化,我有树表:productsproducts-vs-ordersorders

  1. products字段:'ProductID','名称','isGratis',...
  2. products-vs-orders字段:'ProductID','OrderID'
  3. orders字段:'OrderID','标题',...
  4. 实际上,我有这样的查询:

    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
    

3 个答案:

答案 0 :(得分: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`

答案 1 :(得分:1)

SUM(products.isGratis)取决于布尔值在内部由数据库表示为单个数字位的事实,因此false = 0且true = 1.

在所有数据库实现中可能不是这种情况。因此,布尔字段上的SUM可能会导致依赖于实现的行为。

在求和之前将布尔值转换为实际的0和1值应该更合适:

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

答案 2 :(得分:0)

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