我是SQL新手。
我需要获得此查询的结果:
Select
Date,
SUM(SumPrice) as Price1,
SUM(SumAmount) as Amount1,
SUM(SumPrice)/SUM(SumAmount) as AVGprice1
FROM [BiSandbox].[dbo].[database]
where Condition = '1'
group by Date
要与此查询的结果对齐:
Select
Date,
SUM(SumPrice) as Price2,
SUM(SumAmount) as Amount2,
SUM(SumPrice)/SUM(SumAmount) as AVGprice2
FROM [BiSandbox].[dbo].[database]
where Condition = '2'
group by Date
它们应排成一行,因为它们按常见的Date列分组。我无法谷歌/搜索解决方案,因为这是一个非常狭隘的问题。连接这两个结果表的正确语法是什么?我可以加入三个吗?
答案 0 :(得分:0)
如果需要,您可以将表格加入到自身中:
SELET
d1.Date,
SUM(d1.SumPrice) as Price1,
SUM(d1.SumAmount) as Amount1,
SUM(d1.SumPrice)/SUM(d1.SumAmount) as AVGprice1
SUM(d2.SumPrice) as Price2,
SUM(d2.SumAmount) as Amount2,
SUM(d2.SumPrice)/SUM(d2.SumAmount) as AVGprice2
FROM [BiSandbox].[dbo].[database] d1
-- or the primary key column you have instead of id
INNER JOIN [BiSandbox].[dbo].[database] d2 on d1.id = d2.id
WHERE d1.Condition = '1'
AND d2.Condition = '2' -- this can be an OR if needed
GROUP BY d1.Date
如果这个答案不满意,请提供更多详情。