同一个表中的大量内部联接

时间:2014-10-10 18:29:04

标签: sql-server-2012

我有一个场景,其中所有项目都在一个名为“table”的表中。我正在为两件事做这件事:

SELECT I.A + J.A AS A, I.B + J.B AS B, I.C + J.C AS C FROM table AS I
INNER JOIN Table AS J
ON I.StartDate = J.StartDate
AND I.EndDate  = J.EndDate
WHERE I.ItemId = 602028
AND   J.ItemId = 602029

我正在为表中的三个项目执行此操作:

SELECT I.A + J.A + K.A AS A, I.B + J.B + K.B AS B, I.C + J.C + K.C AS C FROM table AS I
INNER JOIN Table AS J
   ON I.StartDate = J.StartDate
  AND I.EndDate   = J.EndDate
INNER JOIN Table AS K
   ON I.StartDate = K.StartDate
  AND I.EndDate   = K.EndDate
WHERE I.ItemId    = 602028
  AND J.ItemId    = 602029
  AND K.ItemId    = 602030

所以现在你知道我想要做什么;直截了当。这是问题所在。加入的项目数在运行时提供,这个数字可以很大,最多200个。我的问题是:最有效的方法是什么?目前,它已经开始变得丑陋,超过5个连接。

3 个答案:

答案 0 :(得分:1)

我不确定你为什么想要别名和转轴,因为我认为你不需要它。

尝试的例子..

declare @table table (ID int, A int, B int, C int, startdate date, enddate date)

insert @table (ID, A, B, C, startdate, enddate)
select 123, 1, 1, 1, '2014-10-10', '2014-10-10'
union all
select 456,2, 2, 2, '2014-10-10', '2014-10-10'
union all
select 789,3, 3, 3, '2014-10-10', '2014-10-10'
union all
select 111,4, 4, 4, '2014-10-11', '2014-10-11'
union all
select 222,4, 4, 4, '2014-10-11', '2014-10-11'


select sum(A) as A, sum(B) as B, sum(C) as C, startdate, enddate
from @table
where ID in (123,456,789, 111, 222)
group by startdate, enddate

答案 1 :(得分:0)

请试试这个!

Select sum(a)as A, sum(b) as B,sum(c) as C from
(select itemid,a,b,c from table t 
where itemid in (602028,602029,...) 
    and exists (select 'x' from table t1 where itemid in (602028,602029,...) and t.startdate=t1.startdate and t.enddate=t1.enddate))a

答案 2 :(得分:0)

您可以在派生表中的表上尝试联合,并对所选日期和项目的列使用sum()

SELECT *
FROM I,
(SELECT SUM(A), SUM(B), SUM(C) 
FROM (SELECT * FROM I UNION
SELECT * FROM J UNION
SELECT * FROM K) UnT

WHERE UnT.STARTDATE = I.STARTDATE 
AND UnT.ENDDATE = I.ENDDATE
AND UnT.ItemId = I.ItemId
AND I.ItemId = 602028

现在你只需要在派生表中联合新表。