子查询没有返回所有结果T-SQL

时间:2013-03-18 19:49:41

标签: sql-server tsql

我有一个Subquery没有返回我正在寻找的结果。我有3个位置在我的条件下并不总是有一个日期范围的订单计数,他们没有返回结果为0.而是我丢失了这些部分的所有其他数据。我确信有更好的查询数据的方法,所以这是我的查询。

SELECT b.Part, b.Location, b.Last_12_Mo, b.Last_6_Mo,
           COUNT(sd.SBINV) AS Order_Count
      FROM (
            SELECT a.Part, a.Location, a.Last_12_Mo,
                   ISNULL(SUM(sd.SBQSHP), 0) AS Last_6_Mo
              FROM (
                    SELECT t3.Part, sd.SBLOC AS Location, ISNULL(SUM(sd.SBQSHP),0) AS Last_12_Mo
                      FROM Top300 t3
                      LEFT JOIN SalesData sd 
                        ON t3.Part   = sd.SBITEM
                       AND sd.SBINDT > '20120315'
                     GROUP BY t3.Part, sd.SBLOC
                    ) AS a 
              LEFT JOIN SalesData sd
                ON a.Part       = sd.SBITEM
               AND sd.SBINDT    > '20121015'
             GROUP BY a.Part, a.Location, a.Last_12_Mo
            ) AS b 
      LEFT JOIN SalesData sd
        ON b.Part       = sd.SBITEM
       AND sd.SBINDT    > '20130110'
     GROUP BY b.Part, b.Location, b.Last_12_Mo, b.Last_6_Mo
     ORDER BY b.Part, b.Location

2 个答案:

答案 0 :(得分:0)

试试这个

SELECT t3.Part, sd.SBLOC AS Location, 
ISNULL(SUM(CASE WHEN sd.SBINDT > '20120315' THEN sd.SBQSHP ELSE 0 END),0) AS Last_12_Mo,
ISNULL(SUM(CASE WHEN sd.SBINDT > '20121015' THEN sd.SBQSHP ELSE 0 END),0) AS Last_6_Mo,
COUNT(CASE WHEN sd.SBINDT > '20130110' THEN sd.SBINV END) AS Order_Count
FROM Top300 t3
LEFT JOIN SalesData sd  ON t3.Part   = sd.SBITEM
GROUP BY t3.Part, sd.SBLOC
ORDER BY t3.Part, sd.SBLOC

根据下面的OP评论,您需要使用位置表连接零件以获取所有零件和位置的组合(注意:更改位置列和表名称以匹配您的位置表)

SELECT t3.Part,  t3.Location, 
ISNULL(SUM(CASE WHEN sd.SBINDT > '20120315' THEN sd.SBQSHP ELSE 0 END),0) AS Last_12_Mo,
ISNULL(SUM(CASE WHEN sd.SBINDT > '20121015' THEN sd.SBQSHP ELSE 0 END),0) AS Last_6_Mo,
COUNT(CASE WHEN sd.SBINDT > '20130110' THEN sd.SBINV END) AS Order_Count
FROM 
(SELECT DISTINCT a.Part, b.Location from Top300 a, LocationTable b)   t3
LEFT JOIN SalesData sd  ON t3.Part   = sd.SBITEM and t3.Location = sd.SBLOC
GROUP BY t3.Part, t3.Location
ORDER BY t3.Part, t3.Location

答案 1 :(得分:0)

在你正在使用的查询中使用:sd.SBINDT> '20121015'

在外面,你正在使用:AND sd.SBINDT> '20130110'

结果在外部查询不会返回之前。