SQL UNION是否包含列的所有可能值?

时间:2015-04-13 19:12:44

标签: sql sql-server

现在,我正在做的是

select t1.Team, t2.Total - SUM(t1.Diff) OVER (ORDER BY t1.DATE DESC ROWS UNBOUNDED PRECEDING) AS Amount
from @trend t1 
INNER JOIN @totalRecordsToday t2 on t1.Team = t2.Team
WHERE t1.Team = 'Team1'
GROUP BY t1.Team, t1.Date, t1.Diff, t2.Total, t1.NewlyAdded, t1.Resolved, t1.Diff
UNION
select t1.Team, t2.Total - SUM(t1.Diff) OVER (ORDER BY t1.DATE DESC ROWS UNBOUNDED PRECEDING) AS Amount
from @trend t1 
INNER JOIN @totalRecordsToday t2 on t1.Team = t2.Team
WHERE t1.Team = 'Team2'
GROUP BY t1.Team, t1.Date, t1.Diff, t2.Total, t1.NewlyAdded, t1.Resolved, t1.Diff

依此类推,对于每个不同的t1.Team值。这是一种硬编码的方法,因为我正在为我知道的t1.Team的每个值做一个联合。有没有办法让我以编程方式对所有不同的t1.Team值进行联合?

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找partition by条款:

select t1.Team,
       t2.Total - SUM(t1.Diff) OVER (PARTITION BY t1.Team
                                     ORDER BY t1.DATE DESC ROWS UNBOUNDED PRECEDING) AS Amount
from @trend t1 INNER JOIN
     @totalRecordsToday t2
     on t1.Team = t2.Team;

我觉得奇怪的是你会知道累积总和而不是partition by。无论如何,所有窗口函数都支持partition by。有些人还支持order by