考虑一下这个sql:
SELECT DATE_FORMAT( Orders.Timestamp, '%Y%m' ) AS Period,
SUM(Price) AS 'Ordersum per month and organisation', Orders.Organisation,
(
SELECT SUM(Amount) AS Returns
FROM Returns
WHERE DATE_FORMAT( Returns.Timestamp, '%Y%m' ) = Period
AND Returns.Organisation = Orders.Organisation
) Returns
FROM Orders
GROUP BY Period, Organisation
每当子查询中的行在主查询中没有等效的句点时,就不会显示该行。原因是查询从订单表中获取其周期,并且当子查询的周期与订单表中的句点不匹配时,它根本不匹配查询。
有没有办法重新格式化此查询以实现我想要的目标?
Sqlfiddle http://sqlfiddle.com/#!9/ace715/1
答案 0 :(得分:1)
您可以使用UNION左右连接,如下所示:
SELECT
ifnull(DATE_FORMAT( Orders.Timestamp,'%Y%m' ),DATE_FORMAT(Returns.Timestamp,'%Y%m' )) AS Period,
SUM(Price) AS 'Ordersum per month and organisation',
ifnull(Orders.Organisation,Returns.Organisation) as 'Organisation',
SUM(Amount) AS 'Returns'
FROM Orders
left JOIN Returns
on DATE_FORMAT( Orders.Timestamp,'%Y%m' ) = DATE_FORMAT(Returns.Timestamp, '%Y%m' )
and Returns.Organisation = Orders.Organisation
GROUP BY Period, Returns.Organisation, Orders.Organisation
union
select ifnull(DATE_FORMAT( Orders.Timestamp, '%Y%m' ),DATE_FORMAT(Returns.Timestamp,'%Y%m' )) AS Period,
SUM(Price) AS 'Ordersum per month and organisation',
ifnull(Orders.Organisation,Returns.Organisation),
SUM(Amount) AS 'Returns'
FROM Orders
right JOIN Returns
on DATE_FORMAT( Orders.Timestamp, '%Y%m' ) = DATE_FORMAT(Returns.Timestamp, '%Y%m' )
and Returns.Organisation = Orders.Organisation
GROUP BY Period, Returns.Organisation, Orders.Organisation