我的sql中有两个查询:
查询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结果是

查询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结果是:

我能把两个查询合并成一个来得到结果吗?
Product_id, product_name, available_start, import, export, refund, available发布于 2018-05-02 02:26:39
使用条件聚合,并将对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 DESChttps://stackoverflow.com/questions/50126280
复制相似问题