需要sql查询方面的帮助吗
您好,我一直在尝试编写一个逐月显示所有销售总额的查询。数据还应按国家和类别分组 每个国家都必须提供所有类别的所有数据,即使数据不存在。我知道我可能需要交叉连接和至少一个左连接,但有几个小时我都不知道怎么做 下面我附上表格和期望的结果,以帮助理解 表产品需要sql查询方面的帮助吗,sql,sql-server,sql-server-2012,Sql,Sql Server,Sql Server 2012,您好,我一直在尝试编写一个逐月显示所有销售总额的查询。数据还应按国家和类别分组 每个国家都必须提供所有类别的所有数据,即使数据不存在。我知道我可能需要交叉连接和至少一个左连接,但有几个小时我都不知道怎么做 下面我附上表格和期望的结果,以帮助理解 表产品 ProductId | Name | CountryId | CategoryId ------------------------------------------ 4 | Ax | 4 |
ProductId | Name | CountryId | CategoryId
------------------------------------------
4 | Ax | 4 | 3
5 | Ball | 5 | 4
表类别
CategoryId | Name
-----------------
3 | Detail
4 | Hurt
餐桌国家
CountryId | CountryName
-----------------------
4 | Germany
5 | Sweden
表销售年度
SaleYearId | Year | ProductId
-----------------------------
1 | 2018 | 4
2 | 2018 | 5
桌面销售
SaleId | SaleYearId | Month1 | Month2 | Month3 | Month4
1 | 1 | 100 | NULL | NULL | NULL
2 | 2 | NULL | 500 | NULL | NULL
期望的结果应该如下所示:
CountryId | CategoryId | Year | Month1 | Month2 | Month3 | Month4
4 | 3 | 2018 | 100 | NULL | NULL | NULL
4 | 4 | NULL | NULL | NULL | NULL | NULL
5 | 3 | NULL | NULL | NULL | NULL | NULL
5 | 4 | 2018 | NULL | 500 | NULL | NULL
DDL和示例数据:如果我正确理解了您的问题,您可以将
交叉联接
用于多个外部联接
:
select c.countryid,
cat.categoryid,
sy.year,
s.month1,
s.month2,
s.month3,
s.month4
from country c cross join category cat
left join product p on c.countryid = p.countryid and cat.categoryid = p.categoryid
left join saleyear sy on p.productid = sy.productid
left join sale s on sy.saleyearid = s.saleyearid
这将创建
类别
和国家
表中所有结果的笛卡尔积。您的示例中的每个结果中有2个-2*2=4个结果。然而,如果你在每一个有5个,你会收到25个结果 不是免费的代码编写服务。您应该尝试自己编写代码。之后,如果你有问题,你可以张贴你已经尝试了一个明确的解释什么是不工作,并提供一个解决方案。我建议你读一个好的问题和答案。另外,请务必采取行动。我不明白您如何获得2018年不存在的数据?例如,您的第二个结果,那一年来自哪里,因为它需要使用外部联接,并且没有任何记录与countryid 4和categoryid 4匹配?我的错误,在第二个结果年中当然应该是空的。我更正了我的帖子。如果您可以将该示例转换为ddl(创建表语句)和dml,那将非常有用(插入声明)。有人必须做的第一件事是在我们开始解决这个问题之前做一些有用的事情。但我对Month1、Month2这样的专栏有点紧张。这看起来很像违反1NF的重复组,这将使这比需要的困难得多。当然,我下次会做。谢谢。这就是我想要的需要,因为我说过我需要汇总数据,所以我让我自己更正你的答案:选择c.countryid、cat.categoryid、sy.year、SUM(s.month1)、SUM(s.month2)、SUM(s.month3)、SUM(s.month4)从国家/地区c交叉连接类别cat left join product p on c.countryid=p.countryid和cat.categoryid=p.categoryid left join saleyear sy on p.productid=sy.productid left join销售s on sy.SALEYEARD=s.SALEYEAREID group by c.countryid,cat.categoryid,sy。year@tylkonachwile很抱歉,没有看到你关于总结的评论。很高兴你去了不过,这不管用!