将我的结果合并到一个平面表格中

发布于 2024-12-20 00:23:11 字数 994 浏览 1 评论 0原文

sql语句

select a.Date, count(a.Id) as Apples from dbo.apples as a group by a.Date

假设我有一个产生结果的

Date      Apples
10/1/2011 4
10/2/2011 6
10/4/2011 8

,并且我有第二个查询

select o.Date, count(o.Id) as Oranges from dbo.Oranges as o group by o.Date

,它产生结果

Date      Oranges
10/2/2011 3
10/3/2011 5
10/4/2011 7

我想将两个结果合并成一个结果,就像

Date      Apples Oranges
10/1/2011 4      0
10/2/2011 6      3
10/3/2011 0      5
10/4/2011 8      7

我尝试过的

select select a.Date, count(a.Id) as Apples from dbo.apples as a group by a.Date
union 
select o.Date, count(o.Id) as Oranges from dbo.Oranges as o group by o.Date

那样,这没有给我预期的结果,我得到的是更多 一样

Date      Apples
10/1/2011 4   
10/2/2011 6
10/2/2011 3
10/3/2011 5
10/4/2011 8
10/4/2011 7

就像没有提到橙子

。最终的sql语句应该是什么样的(我更喜欢高性能和简洁而不是不)。

Suppose I have an sql statement

select a.Date, count(a.Id) as Apples from dbo.apples as a group by a.Date

which yields a result

Date      Apples
10/1/2011 4
10/2/2011 6
10/4/2011 8

And I have a second query

select o.Date, count(o.Id) as Oranges from dbo.Oranges as o group by o.Date

which yields the result

Date      Oranges
10/2/2011 3
10/3/2011 5
10/4/2011 7

I would like to combine the two results into a single result like

Date      Apples Oranges
10/1/2011 4      0
10/2/2011 6      3
10/3/2011 0      5
10/4/2011 8      7

I tried

select select a.Date, count(a.Id) as Apples from dbo.apples as a group by a.Date
union 
select o.Date, count(o.Id) as Oranges from dbo.Oranges as o group by o.Date

which didn't give me the expected results, what I got was more like

Date      Apples
10/1/2011 4   
10/2/2011 6
10/2/2011 3
10/3/2011 5
10/4/2011 8
10/4/2011 7

with no mention of Oranges.

What should the final sql statement look like (I prefer performant and concise over not).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瀟灑尐姊 2024-12-27 00:23:11
select date,sum(apples) as apples,sum(oranges) as Oranges
from
(
select a.Date as theDate, count(a.Id) as Apples,0 as Oranges 
from dbo.apples as a group by a.Date 
union all
select o.Date, 0 as apples, count(o.Id) as Oranges
 from dbo.Oranges as o 
 group by o.Date 
) xx
group by theDate
select date,sum(apples) as apples,sum(oranges) as Oranges
from
(
select a.Date as theDate, count(a.Id) as Apples,0 as Oranges 
from dbo.apples as a group by a.Date 
union all
select o.Date, 0 as apples, count(o.Id) as Oranges
 from dbo.Oranges as o 
 group by o.Date 
) xx
group by theDate
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文