SQL QUERY:连接两个表

时间:2013-11-05 10:33:20

标签: sql sql-server

我在获取正确数据时遇到问题......

我有两个表, tblbuilding和tbldata。

这是我的 tblbuilding

enter image description here

这是我的 tbldata

enter image description here

我的疑问:

我的fldWeek在这里是“第3周”:

SELECT tblbuilding.fldBldgName
      ,tblbuilding.fldNetname
      ,MAX(tbldata.fldDuration) AS fldDuration
      ,tbldata.fldWeek
      ,tbldata.fldYear
FROM tblbuilding AS tblbuilding_1 
    LEFT OUTER JOIN tbldata ON tblbuilding_1.fldBldgName = tbldata.fldBldgName 
    CROSS JOIN tblbuilding
WHERE (tblbuilding.fldNetname = 'LRT - 2') 
    AND (tbldata.fldWeek = 'Week 3' OR tbldata.fldWeek IS NULL)
    AND (tbldata.fldYear = '2013' OR tbldata.fldYear IS NULL)
GROUP BY tbldata.fldWeek
        ,tblbuilding.fldBldgName
        ,tblbuilding.fldNetname
        ,tbldata.fldYear
ORDER BY tblbuilding.fldBldgName

上述查询的结果是:

enter image description here

哪个是正确的......

但当我将fldWeek改为“第2周”时

结果是:

enter image description here

正确的结果应该是......“假设我在WEEK 2中只有两个NOT NULL”

enter image description here

...谢谢

1 个答案:

答案 0 :(得分:3)

我认为你不需要获得笛卡尔积。

仅使用LEFT JOIN尝试此操作。

SELECT  a.ID,
        a.fldBldgName,
        b.fldDuration,
        b.fldWeek,
        b.fldYear
FROM    tblBuilding a
        LEFT JOIN tblData b
            ON  a.fldBldgName = b.fldBldgName
                AND b.fldWeek = 'Week 3'
                AND b.fldYear = '2013'
WHERE   a.fldNetname = 'LRT - 2'