修复“X在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中”

时间:2012-10-25 03:07:01

标签: sql 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子句中。

提前致谢。

4 个答案:

答案 0 :(得分:4)

SELECT语句中不是聚合函数的所有列(在您的示例中,除了sum(d.qtyfulfi)之外的所有列都需要在GROUP BY子句中。

只需按照分组层次结构的顺序列出它们(在我脑海中,我想象的从更少到更具体)。

答案 1 :(得分:4)

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

答案 2 :(得分: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

答案 3 :(得分: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