关于SQL Distinct子句

时间:2013-06-04 16:38:19

标签: sql sql-server-2008

我正在尝试输出以下数据,每个位置只有一行。现在它显示: 120 .... 120 ... 120 ...

我试图让它将所有值加总为一行为120,一行为123,一行为128,等等。我认为这与DISTINCT条款有关但我有点大脑看着这个......

SELECT ICLOCATION.LOCATION,
       ICLOCATION.NAME,
       ITEMMAST.ITEM,
       ITEMMAST.DESCRIPTION,
       ITEMLOC.SOH_QTY,
       OnOrder,
       AllocQty,
       SUM(ITEMLOC.SOH_QTY + t.OnOrder - t.AllocQty) AS NetOnHand
FROM   (SELECT ITEMLOC.ITEM,
               SUM(ISNULL(ITEMLOC.ONORDER_QTY, 0) + ITEMLOC.INTRANS_QTY + ITEMLOC.WIP_QTY)                                 AS OnOrder,
               SUM(ITEMLOC.ALLOC_QTY + ITEMLOC.UNALLOC_QTY + ITEMLOC.BACKORD_QTY + ITEMLOC.IN_PROC_QTY + ITEMLOC.HOLD_QTY) AS AllocQty
        FROM   ITEMLOC
        GROUP  BY ITEMLOC.ITEM) t
       INNER JOIN ITEMLOC
         ON ITEMLOC.ITEM = t.ITEM
       INNER JOIN ITEMMAST
         ON ITEMLOC.ITEM = ITEMMAST.ITEM
       INNER JOIN ICLOCATION
         ON ITEMLOC.COMPANY = ICLOCATION.COMPANY
WHERE  ( ICLOCATION.LOCATION = '120'
          OR ICLOCATION.LOCATION = '123'
          OR ICLOCATION.LOCATION = '128'
          OR ICLOCATION.LOCATION = '129'
          OR ICLOCATION.LOCATION = 'HD41D'
          OR ICLOCATION.LOCATION = 'HD21H'
          OR ICLOCATION.LOCATION = 'HD91H' )
       AND ITEMMAST.ITEM = '0210950'
GROUP  BY ITEMMAST.ITEM,
          ICLOCATION.LOCATION,
          ICLOCATION.NAME,
          ITEMMAST.DESCRIPTION,
          ITEMLOC.SOH_QTY,
          ITEMLOC.ITEM,
          OnOrder,
          AllocQty
ORDER  BY ICLOCATION.LOCATION,
          ITEMMAST.ITEM 

1 个答案:

答案 0 :(得分:1)

削减你的GROUP BY。它首先按ITEMMAST.ITEM分组,然后ICLOCATION.LOCATION分组。切换订单或摆脱ITEM

此外,无关,您可能希望通过在WHERE语句中使用IN运算符来清理它。即。

ICLOCATION.LOCATION IN ('120', '123', '128', '129', 'HD41D', 'HD21H', 'HD91H')