2012-10-25 59 views
1

早上好。下面我有一個查詢需要總數量每貨號修復「X在選擇列表中無效,因爲它不包含在聚合函數或GROUP BY子句中」

select h.cstponbr 'Customer PO No.', 
     h.sopnumbe 'Invoice No.', 
     d.itemnmbr 'Item No.', 
     d.itemdesc 'Item Description', 
     d.qtyfulfi 'Qty Fulfilled', 
     sum(d.qtyfulfi) 'Total Qty Fulufilled' 
from sop10100 h 
inner join sop10200 d on (h.sopnumbe = d.sopnumbe) 
where h.cstponbr = @CUSTPONUM 
group by d.itemnmbr 

我將如何安排我的查詢,以便我會盡量避免以下錯誤達到的。

列「sop10100.CSTPONBR」在選擇列表中無效,因爲它是 不包含在聚合函數或GROUP BY子句。

在此先感謝。

+1

這意味着正是它說。在相關問題上取得一個高峯。 – 2012-10-25 03:09:44

+0

它是Sql Server嗎?如果是,哪個版本? –

回答

1

修改您的查詢到這一點,

select h.cstponbr 'Customer PO No.', 
     h.sopnumbe 'Invoice No.', 
     d.itemnmbr 'Item No.', 
     d.itemdesc 'Item Description', 
     d.qtyfulfi 'Qty Fulfilled', 
     c.totalCount 'Total Qty Fulufilled' 
from sop10100 h 
     inner join sop10200 d 
      on (h.sopnumbe = d.sopnumbe) 
     INNER JOIN 
     (
      SELECT sopnumbe, SUM(qtyfulfi) totalCount 
      FROM sop10200 
      GROUP BY sopnumbe 
     ) c ON c.sopnumbe = h.sopnumbe 
where h.cstponbr = @CUSTPONUM 
4

在SELECT語句中的所有列不屬於聚合函數(在你的榜樣,除了總和(d.qtyfulfi)都必須在GROUP BY

條款,只要一一列舉在分組層次的順序(在我的腦子裏,我從少到多具體的想象)。

4
you can use only columns that are functionally depended on group by clause . 
1

假設Sql Server的2005+,這應該工作

;With Cte As(
Select 
     h.cstponbr 'Customer PO No.', 
     h.sopnumbe 'Invoice No.', 
     d.itemnmbr 'Item No.', 
     d.itemdesc 'Item Description', 
     d.qtyfulfi 'Qty Fulfilled', 
     sum(d.qtyfulfi) Over(Partition By d.itemnmbr) 'Total Qty Fulufilled', 
     Rn =Row_Number() Over(Partition By d.itemnmbr Order By (Select 1)) 
from sop10100 h 
inner join sop10200 d on (h.sopnumbe = d.sopnumbe) 
where h.cstponbr = @CUSTPONUM ) 

Select * 
From Cte 
Where Rn = 1 

一個更通用的應該是

select h.cstponbr 'Customer PO No.', 
     h.sopnumbe 'Invoice No.', 
     X.ItemNo, 
     X.ItemDescription, 
     X.QtyFulfilled, 
     X.TotalQtyFulufilled 
from sop10100 h 
inner join 
      (Select 
       X.ItemNo 
       ,d.itemdesc 'ItemDescription' 
       ,d.qtyfulfi 'QtyFulfilled' 
       ,d.sopnumbe 
       ,X.TotalQtyFulufilled 
       From sop10200 d 
      Inner Join 
       (Select d.itemnmbr 'ItemNo',sum(d.qtyfulfi)'TotalQtyFulufilled' 
       From sop10200 d 
       group by d.itemnmbr)X 
      On d.itemnmbr = X.ItemNo)X 
on (h.sopnumbe = X.sopnumbe) 
where h.cstponbr = @CUSTPONUM 
相關問題