1

早上好。我在下面有一个查询,要求每个项目编号的总数量。

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

4 回答 4

4

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

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

于 2012-10-25T03:16:58.803 回答
4
you can use only columns that are functionally depended on group by clause .
于 2012-10-25T03:18:33.997 回答
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
于 2012-10-25T03:13:14.447 回答
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
于 2012-10-25T03:33:17.650 回答