SQL server按不同列分组并创建新变量

SQL server按不同列分组并创建新变量,sql,sql-server,group-by,Sql,Sql Server,Group By,我有一张像这样的桌子 Date X1 X2 Y 2010 1 1 120 2010 1 2 130 2010 1 3 140 2010 2 1 150 2010 2 2 160 2010 2 3 170 2011 1 1 180 2011 1 2 190 2011 1 3 200 2011 2 1 210 2011 2 2 220 2011 2 3 230 等等。我想计算Y的总和,同时分别为两个X变量和日期变量分组。最后,我需要在两个新列中使用两

我有一张像这样的桌子

Date X1 X2 Y
2010 1  1  120
2010 1  2  130
2010 1  3  140
2010 2  1  150
2010 2  2  160
2010 2  3  170
2011 1  1  180
2011 1  2  190
2011 1  3  200
2011 2  1  210
2011 2  2  220
2011 2  3  230
等等。我想计算Y的总和,同时分别为两个X变量和日期变量分组。最后,我需要在两个新列中使用两个Y和,其中只有1个X变量(因为X1和X2的值代表相同的概念)。输出看起来像

Date X Y1           Y2
2010 1 120+130+140  120+150
2010 2 150+160+170  130+160
2010 3 0            140+170
2011 1 180+190+200  180+210

等等。是否有一种有效的方法(性能是关键)?我知道我可以使用窗口函数在两列中独立地获取两个X的总和,但是我如何才能将结果分组(日期,X)?

您可以使用
UNION ALL
查询在每个X值之间拆分
Y
值,然后在外部查询中求和:

SELECT [Date], X, SUM(Y1) AS Y1, SUM(Y2) AS Y2
FROM (
  SELECT [Date], X1 AS X, Y AS Y1, 0 AS Y2
  FROM data
  UNION ALL 
  SELECT [Date], X2 AS X, 0, Y
  FROM data
) d
GROUP BY [Date], X
ORDER BY [Date], X
输出:

Date    X   Y1      Y2
2010    1   390     270
2010    2   480     290
2010    3   0       310
2011    1   570     390
2011    2   660     410
2011    3   0       430

这是两个查询的组合:

select
  coalesce(t1.date, t2.date) as date,
  coalesce(t1.x, t2.x) as x,
  coalesce(t1.total, 0) as y1,
  coalesce(t2.total, 0) as y2
from
(
  select date, x1 as x, sum (y) as total
  from mytable
  group by date, x1
) t1
full outer join
(
  select date, x2 as x, sum (y) as total
  from mytable
  group by date, x2
) t2 on t2.date = t1.date and t2.x = t1.x
order by date, x;
我建议查询使用以下索引:

create index idx1 on mytable (date, x1, y);
create index idx2 on mytable (date, x2, y);
这些索引提供预先排序的数据,因此分组和连接应该很快