0

我有一个不返回我正在寻找的结果的子查询。在我的情况下,我有 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
4

2 回答 2

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

根据下面的 OPs 评论,您需要将部件与位置表连接起来以获得所有部件和位置的组合(注意:更改位置列和表名称以匹配您的位置表)

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
于 2013-03-18T19:57:04.210 回答
0

伙计,在您使用的查询中:sd.SBINDT > '20121015'

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

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

于 2013-03-18T19:57:52.273 回答