Create table #test (Type nvarchar(250), DayCount int, WeekCount int)
insert into #test values ('A/C', 1346, 8095)
insert into #test values ('Cooler', 13, 36)
insert into #test values ('Table Fan', 0, 5)
insert into #test values ('Ceiling Fan', 186, 4507)
输出应为:
Type DayCount WeekCount TotDayCount TotWeekCount
----------------------------------------------------------
A/C 1346 8095 1445 12643
Cooler 13 36 1445 12643
Table Fan 0 5 1445 12643
Ceiling Fan 186 4507 1445 12643
答案 0 :(得分:0)
使用子查询:
SELECT Type,
DayCount,
WeekCount,
TotDayCount = ( SELECT SUM(DayCount)
FROM Test ),
TotWeekCount = ( SELECT SUM(WeekCount)
FROM Test )
FROM Test
您不必担心每行都会执行这些查询。 SQL-Server优化器非常智能,只能计算一次。
答案 1 :(得分:0)
假设您使用的是相当现代的SQL Server版本,则可以使用twitteR
:
SUM OVER
以下是有关select
t1.*,
sum(daycount) over () as DayTotal,
sum(weekcount) over () WeekCount
from
test t1
子句的更多信息:
Clicky!