有没有办法在 SQL Server 中编写这样的查询,而不使用两次选择然后加入?
select trans_date, datepart(HOUR,trans_time) as hour,
(datepart(MINUTE,trans_time)/30)*30 as minute,
case
when paper_number = 11111/*paperA*/
then sum(t1.price*t1.amount)/SUM(t1.amount)*100
end as avgA,
case
when paper_number = 22222/*PaperB*/
then sum(t1.price*t1.amount)/SUM(t1.amount)*100
end as avgB
from dbo.transactions t1
where trans_date = '2006-01-01' and (paper_number = 11111 or paper_number = 22222)
group by trans_date, datepart(HOUR,trans_time), datepart(MINUTE,trans_time)/30
order by hour, minute
SQL Server 要求我将 paper_number 添加到分组依据,并在我这样做时返回空值
trans_date hour minute avgA avgB
2006-01-01 9 30 1802.57199725463 NULL
2006-01-01 9 30 NULL 169125.886524823
2006-01-01 10 0 1804.04742534103 NULL
2006-01-01 10 0 NULL 169077.777777778
2006-01-01 10 30 1806.18773535637 NULL
2006-01-01 10 30 NULL 170274.550381867
2006-01-01 11 0 1804.43466045433 NULL
2006-01-01 11 0 NULL 170743.4
2006-01-01 11 30 1807.04532012137 NULL
2006-01-01 11 30 NULL 171307.00280112