将多个SQL select语句组合为列
将多个select语句组合为一列,不会给出所需的输出。我错过了什么?Group by子句未按预期工作。我是否也需要将GroupBy用于外部选择 SQL查询:将多个SQL select语句组合为列,sql,sql-server,tsql,stored-procedures,Sql,Sql Server,Tsql,Stored Procedures,将多个select语句组合为一列,不会给出所需的输出。我错过了什么?Group by子句未按预期工作。我是否也需要将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],
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
我正在寻找的产出:应该显示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)
选择年份(如TestDate),月份(如TestDate),
求和(当e.pID为0时,则为1,否则为0结束)作为连接点,
总和(当e.pID=0时,则为1,否则为0结束)作为非点
来自dbo.e
其中e.TestDate介于“2020-01-01”和“2020-12-31”之间
按年份(如TestDate)、月份(如TestDate)分组
按年份(如TestDate)、月份(如TestDate)排序的订单
@DaleK删除了我之前发布的图片,谢谢。它有效了(谢谢:),因为我已经将问题更新为更一般的问题。我根据它编辑了答案。
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)