没有双值的JOIN

时间:2011-02-14 08:20:22

标签: sql

我有查询

SELECT frst.Date,t1.Value
from
[ArchiveAnalog] frst
LEFT JOIN
    (SELECT Date,Value FROM
    [ArchiveAnalog] scnd
    WHERE scnd.ID = 1) t1
    ON t1.Date = frst.Date

order by frst.Date

但是Join第二次插入值(不是主节点组)

如果我执行GROUP BY frst.Date,我有错误,我不能使用t1值。

如何在不添加其他行的情况下进行此JOIN?

Martin 我想仅在ID = 1时才显示完整的日期和值,同时我想添加t2值列等,如下所示:

SELECT frst.Date,t1.Value,t2.Value
from
[ArchiveAnalog] frst
LEFT JOIN
    (SELECT Date,Value FROM
    [ArchiveAnalog] scnd
    WHERE scnd.ID = 1) t1
    ON t1.Date = frst.Date
LEFT JOIN
(SELECT Date,Value FROM
[ArchiveAnalog] scnd
WHERE scnd.ID = 2) t2
ON frst.Date = t2.Date

这里我有x2个额外的行:S值加倍,所以我需要用一些方法对它们进行分组。

2 个答案:

答案 0 :(得分:1)

您需要在主查询中DISTINCT(如果您需要t1中最多有一行),或GROUP BY。如果您使用GROUP BY,则需要汇总t1.Value(例如求和,连接等)。

答案 1 :(得分:1)

这可以满足您的需求吗?

SELECT Date , 
       MAX(CASE WHEN ID=1 THEN Value END) AS val1,
       MAX(CASE WHEN ID=2 THEN Value END) AS val2
FROM [ArchiveAnalog]
WHERE ID IN (1,2) /*<-- Not sure if you need this line without seeing your data*/
GROUP BY Date