[英]Combining multiple SQL select statements as columns
将多个 select 语句组合为一列,不会给出所需的 output。 我在这里缺少什么? Group by 子句未按预期工作。 我还需要对外部 Select 使用 GroupBy 吗?
SQL 查询:
use [Test_DB]
SELECT a.fldYear,a.fldMonth, a.ConnPoints,b.NonConnPoints from
(Select DATEPART(YEAR, e.TestDate) as [fldYear], DATENAME(month,e.TestDate) as [fldMonth], count(e.equipid) as [ConnPoints] from dbo.equip e
where e.pID<>0 and e.TestDate between '01-01-2020' and '12-31-2020'
Group By DATEPART(year,e.TestDate), DATENAME(month,e.TestDate), DATEPART(month,e.TestDate)) as a,
(Select DATEPART(YEAR, e.TestDate) as [fldYear], DATENAME(month,e.TestDate) as [fldMonth], count(e.equipid) as [NonConnPoints] from dbo.equip e
where e.PID=0 and e.TestDate between '01-01-2020' and '12-31-2020'
Group By DATEPART(year,e.TestDate), DATENAME(month,e.TestDate), DATEPART(month,e.TestDate)) as b
当前 Output:显示 2020 年的 144 行数据
fldYear fldMonth ConnPoints NonConnPoints
2020 January 13456 73456
2020 February 8345666 8375666
2020 January 13456 8366
2020 April 734569 334469
2020 February 8345666 13456
2020 June 33456 3456
2020 April 734569 45663
Output 我正在寻找:应该显示 2020 年 12 个月的数据
fldYear fldMonth ConnPoints NonConnPoints
2020 January 13456 73456
2020 February 8345666 8375666
2020 March 734566 8366
2020 April 734569 334469
2020 May 43456 13456
2020 June 33456 3456
2020 July 5345663 45663
2020 August 345661 75661
2020 September 345662 245662
2020 November 345668 645668
2020 December 534566 538866
你只想要条件聚合:
select year(e.TestDate), month(e.TestDate),
sum(case when e.pID <> 0 then 1 else 0 end) as ConnPoints,
sum(case when e.pID = 0 then 1 else 0 end) as NonConnPoints
from dbo.equip e
where e.TestDate between '2020-01-01' and '2020-12-31'
group by year(e.TestDate), month(e.TestDate)
order by year(e.TestDate), month(e.TestDate)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.