我尝试整合“'单位'和'金额'用于删除已反转的行项目(苹果)的字段,但它还将其他行项目(Pears)分组,我需要在单独的行中列出。有没有办法在不使用聚合函数的情况下删除反转的行项目?
SELECT Account, Code, Item, SUM(Units) As ‘Total Units’, SUM(Amount) AS ‘TotalAmt’
FROM Fruit
GROUP BY Account, Code, Item
表
Account Code Item Units Amount
------- -------- ------- ----- ------
10325 5972 Apple 1 .50
10325 5972 Apple -1 -.50
10325 7231 Pear 1 .62
10325 7231 Pear 1 .62
10431 5972 Apple 1 .50
RESULT
TABLE
Account Code Item Units Amount
------- -------- ------- ----- ------
10325 7231 Pear 2 1.24
10431 5972 Apple 1 .50
答案 0 :(得分:0)
试试这段代码:
SELECT Account, Code, Item, SUM(Units) As ‘Total Units’, SUM(Amount) AS ‘TotalAmt’
FROM Fruit
GROUP BY Account, Code, Item
having sum(Units)>0
答案 1 :(得分:0)
假设我们有可用的窗口函数,我们可以创建按帐户,项目单位和金额划分的行号,在这些字段上加入然后加入RowNumber,这样我们就不会为多个销售分配回报。
回报可能与错误的销售有关,所以我不喜欢这种回应;但如果我们不关心这一点,只想消除销售记录......这应该做到。
假设:只有回报才是负数单位和负数。
SELECT Sales.Account, Sales.Code, Sales.Item, Sales.Units, Sales.Amount
FROM (SELECT Account, Code, Item, Units , Amount, Row_number() over (partition by Account, Code, Item, Units, Amount order by UniqSeq) RN
FROM Fruit
WHERE UNITS >= 0) Sales
LEFT JOIN (SELECT Account, Code, Item, Units , Amount, Row_number() over (partition by Account, Code, Item, Units, Amount order by UniqSeq) RN
FROM Fruit
WHERE UNITS < 0
AND amount < 0) Returns
on Sales.Account = Returns.Account
and Sales.Code = Returns.Code
and Sales.Item = Returns.Item
and Sales.Units *-1 = Returns.Units
and Sales.Amount *-1 = Returns.Amount
and Sales.RN = Returns.RN
WHERE Returns.Account is null
和OrderID,或每行自动递增的ID ......
如果我假设oracle:
with Fruit (uniqSeq, Account, Code, Item, Units, Amount) as
(
select 1, 10325, 5972, 'Apple', 1, .50 from dual union all
select 2, 10325, 5972, 'Apple', -1, -.50 from dual union all
select 3, 10325, 7231, 'Pear', 1, .62 from dual union all
select 4, 10325, 7231, 'Pear', 1, .62 from dual union all
select 5, 10431, 5972, 'Apple', 1, .50 from dual )
SELECT Sales.Account, Sales.Code, Sales.Item, Sales.Units, Sales.Amount
FROM (SELECT Account, Code, Item, Units , Amount, Row_number() over (partition by Account, Code, Item, Units, Amount order by UniqSeq) RN
FROM Fruit
WHERE UNITS >= 0) Sales
LEFT JOIN (SELECT Account, Code, Item, Units , Amount, Row_number() over (partition by Account, Code, Item, Units, Amount order by UniqSeq) RN
FROM Fruit
WHERE UNITS < 0
AND amount < 0) Returns
on Sales.Account = Returns.Account
and Sales.Code = Returns.Code
and Sales.Item = Returns.Item
and Sales.Units *-1 = Returns.Units
and Sales.Amount *-1 = Returns.Amount
and Sales.RN = Returns.RN
WHERE Returns.Account is null
这里是带有连接的视图,显示“返回”派生表,消除了where子句......所以你可以看到为什么过滤对return.account为null的工作......