3个查询合并和计划创建图表

时间:2013-03-07 05:12:50

标签: mysql sql

Product_Name: Pillow, Pillow Case
Color: Red, Blue and Green
Status: Available, Sold

我有3个单独的查询计算ff:

  1. 计算可用枕头总数
  2. 计算出售的枕头总数
  3. 可用超卖
  4. 之间的差异

    我打算创建一个关于各个查询的图表,但无法弄清楚将3个查询合并为1 仍会产生相同的输出,或者是否可能?

    其中一个查询: (我只会添加Status ='Sold'的Where条件)

    SELECT COUNT( * ) AS totalAvailable, Product_Name, Color, Status 
    FROM Product
    GROUP BY Product, Color
    

1 个答案:

答案 0 :(得分:1)

SELECT  Product_name,
        totalAvailable,
        totalSold,
        totalAvailable - totalSold AS ProductDifference
FROM
        (
            SELECT  Product_name,
                    SUM(CASE WHEN Status = 'Available' THEN 1 ELSE 0 END) totalAvailable,
                    SUM(CASE WHEN Status = 'Sold' THEN 1 ELSE 0 END) totalSold
            FROM    tableName
            GROUP   BY Product_name
        ) s