Concat 2在mysql中查询库存报告

时间:2018-05-02 02:18:52

标签: mysql sql

我的sql中有2个查询:

查询1

SELECT
    product_id, 
    product_name, 
    SUM(case when type = "I" then quantity else 0 end) as import, 
    SUM(case when type = "O" then quantity else 0 end) as export, 
    SUM(case when type = "R" then quantity else 0 end) as refund, 
    (
        SUM(case when type = "R" then quantity else 0 end)
        - SUM(case when type = "O" then quantity else 0 end)
        +SUM(case when type = "I" then quantity else 0 end)
    ) as available

FROM
    `i1ntl_ldn_soft_inventory_detail`
WHERE 
    product_id = 2772 
    and date(refdate) < "2018-03-09" 
    and date(refdate)>= "2018-03-01"
GROUP by 
    product_id
ORDER BY 
    `import` DESC

结果是

enter image description here

查询2

SELECT 
    product_id, 
    product_name, 
    (
        SUM(case when type = "R" then quantity else 0 end) 
        - SUM(case when type = "O" then quantity else 0 end)
        +SUM(case when type = "I" then quantity else 0 end)
    ) as available_start
FROM
    `i1ntl_ldn_soft_inventory_detail` 
WHERE 
    product_id = 2772 
    and date(refdate) < "2018-03-01"
GROUP by
    product_id

结果是:

enter image description here

我可以将2个查询合并为1以获得结果

Product_id, product_name, available_start, import, export, refund, available

1 个答案:

答案 0 :(得分:1)

使用条件聚合,并将refdate上的检查移至CASE表达式。然后,您可以使用单个查询。

SELECT
    product_id,
    product_name,
    SUM(CASE WHEN type = 'I' AND DATE(refdate) >= '2018-03-01' AND
             DATE(refdate) < '2018-03-09' THEN quantity ELSE 0 END) AS import,
    SUM(CASE WHEN type = 'O' AND DATE(refdate) >= '2018-03-01' AND
             DATE(refdate) < '2018-03-09' THEN quantity ELSE 0 END) AS export,
    SUM(CASE WHEN type = 'R' AND DATE(refdate) >= '2018-03-01' AND
             DATE(refdate) < '2018-03-09' THEN quantity ELSE 0 END) AS refund,
    SUM(CASE WHEN type IN ('R', 'I') AND DATE(refdate) >= '2018-03-01' AND
             DATE(refdate) < '2018-03-09' THEN quantity ELSE 0 END) -
        SUM(CASE WHEN type = 'O' AND DATE(refdate) >= '2018-03-01' AND
                 DATE(refdate) < '2018-03-09' THEN quantity ELSE 0 END) AS available,
    SUM(CASE WHEN type IN ('R', 'I') AND DATE(refdate) < '2018-03-01'
             THEN quantity ELSE 0 END) -
        SUM(CASE WHEN type = 'O' AND DATE(refdate) < '2018-03-01'
                 THEN quantity ELSE 0 END) AS available_start
FROM i1ntl_ldn_soft_inventory_detail
WHERE product_id = 2772
GROUP by product_id
ORDER BY import DESC