2012-10-25 55 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 
相关问题