在3个条件下左连接3次相同的表倍数结果

时间:2012-02-22 21:00:34

标签: sql-server-2008 stored-procedures

这是事情,我有这样的表

第一个

ID1 ID2 ID3

第二

ID1 ID2 ID3 month, value

我需要的是为这3个ID的每个组合获取三个月的值,我就是这样:

SELECT a.ID1, a.ID2, a.ID3, b.value, c.value, d.value
FROM Table1 a

LEFT JOIN Table2 b
ON a.ID1 = b.ID1
AND a.ID2 = b.ID2
AND a.ID3 = b.ID3
WHERE month=2


LEFT JOIN Table2 c
ON a.ID1 = c.ID1
AND a.ID2 = c.ID2
AND a.ID3 = c.ID3
WHERE month=3


LEFT JOIN Table2 d
ON a.ID1 = d.ID1
AND a.ID2 = d.ID2
AND a.ID3 = d.ID3
WHERE month=4

我的价值倍增。

知道为什么会这样,或者对其他方法有什么建议吗?

感谢。

2 个答案:

答案 0 :(得分:1)

假设你想要根据今天的日期接下来的3个月(下个月和接下来的两个月),你可以这样做(你也可以将@base设置为任何特定的日期,以获得接下来的三个月):

DECLARE @base DATETIME = GETDATE();

;WITH x AS
(
    SELECT a.ID1, a.ID2, a.ID3, 
      m = DATEADD(MONTH, b.[Month]-1, RTRIM(b.[Year])+'0101'), b.value
    FROM dbo.Table1 AS a INNER JOIN dbo.Table2 AS b 
    ON a.ID1 = b.ID1 AND a.ID2 = b.ID2 AND a.ID3 = b.ID3
), y AS
(
    SELECT ID1, ID2, ID3, m, md = DATEDIFF(MONTH, @base, m), value
    FROM x
    WHERE DATEDIFF(MONTH, @base, m) BETWEEN 1 AND 3
)
SELECT ID1, ID2, ID3, 
    BValue = SUM(CASE WHEN md = 1 THEN value END),
    CValue = SUM(CASE WHEN md = 2 THEN value END),
    DValue = SUM(CASE WHEN md = 3 THEN value END)
FROM y 
GROUP BY ID1, ID2, ID3;

答案 1 :(得分:0)

您可以将WHERE month=x放在inner join的正确位置,如果是outer join,它将无法正常工作。