0

I have a problem in getting the correct data...

I have two tables, tblbuilding and tbldata.

Here's my tblbuilding:

enter image description here

Here's my tbldata:

enter image description here

my query:

My fldWeek here is "Week 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

The result of the query above is:

enter image description here

Which is correct....

but when I changed the fldWeek to "Week 2"

the result is:

enter image description here

The correct result should be...."assuming that I have only two NOT NULL in WEEK 2"

enter image description here

Thanks....

4

1 回答 1

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' 
于 2013-11-05T10:53:40.817 回答