如何解决选择求和显示左连接SQL语句中的空值
我有三个表,预期结果如下,但我不知道如何更正我的sql语句。
1st place 2nd place 3rd place 1st place value 2nd place value 3rd place value
factor1 factor2 factor3 1 1 1
factor1 factor2 factor3 1 1 2
factor1 factor2 factor3 1 1 3
… … … … … …
factor8 factor9 factor10 15 15 15
历史
select history.company,history.ghacct,rpt_revenue.revenue,rpt_revenue.other,isnull(guest.stay,0) as stay,isnull(guest.nights,0) as nights
from history
left join(select company,count(*) as stay,sum(nights) as nights from guest group by company) guest on guest.company=history.company
left join (select ghacct,sum(revenue) as revenue,sum(other) as other
from rpt_revenue group by ghacct) rpt_revenue on rpt_revenue.ghacct=history.ghacct
where history.type='c' group by history.company,guest.stay,guest.nights order by history.company asc;
客人
ghacct company type
33 JOINT LTD 10010205687 c
3B GLOBAL 10010350619 c
3E FASHION 10010244145 c
3P INT'L 10010112089 c
rpt_revenue
company stay nights
33 JOINT LTD 01/01/2009 1
33 JOINT LTD 01/06/2009 1
3B GLOBAL 10/02/2019 2
3E FASHION 09/25/2008 6
3P INT'L 08/26/2009 3
3P INT'L 04/26/2010 9
结果
ghacct revenue other
10010205687 20 10
10010205687 10 10
10010350619 30 2
10010244145 15 3
10010112089 16 8
10010112089 4 2
预期结果
company ghacct revenue other stay nights
33 JOINT LTD 10010205687 NULL NULL 2 2
3B GLOBAL 10010350619 NULL NULL 1 2
3E FASHION 10010244145 NULL NULL 1 6
3P INT'L 10010112089 NULL NULL 2 12
解决方法
我认为您当前查询的主要问题在于GROUP BY
子句,该子句实际上仅应按公司和帐户进行汇总。此外,您可能希望将ISNULL
用于收入和其他金额,因为您已经在住宿和住宿期间使用了。
SELECT
h.company,h.ghacct,ISNULL(rr.revenue,0) AS revenue,ISNULL(rr.other,0) AS other,ISNULL(g.stay,0) AS stay,ISNULL(g.nights,0) AS nights
FROM history h
LEFT JOIN
(
SELECT company,COUNT(*) AS stay,SUM(nights) AS nights
FROM guest
GROUP BY company
) g
ON g.company = h.company
LEFT JOIN
(
SELECT ghacct,SUM(revenue) AS revenue,SUM(other) AS other
FROM rpt_revenue
GROUP BY ghacct
) rr
ON rr.ghacct = h.ghacct
WHERE
h.type = 'c'
GROUP BY
h.company,h.ghacct
ORDER BY
h.company;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。