0

I'm struggling with this specific Access 2010 SQL query for quite some time now. Let me first show you what my table looks like:

customerID     value
123456789        100
123456789       -100
123456789        300
123456789       -300
123456789        150
123456789       -150
123456789        200
123456789        200
987654321        500
987654321       -500
987654321        200
987654321       -200
987654321        210
987654321        210

You see I have multiple entries for one customerID with several values. These values can be positive and negative. Negative values represent corrections so the corresponding positive value "gets nulled".

What I need to query now is the maximum value of all maximum values per customerID. In the example above, the maximum value of customerID 123456789 is 200, because all other values on this customerID annul each other. The maximum value on customerID 987654321 hence is 210.

Ultimately my query should return the value of 210 as the maximum out of all maximum values per customerID that didn't get corrected/anulled by negative values.

Can you please help me with this?

Edit: Added (duplicate) values 200 and 210 to both customerIDs to make clear that a SUM() wont work here.

Edit #2: Here's some (nearly) real life data: http://pastebin.com/TbNRTw5A

4

1 回答 1

1

我不知道这是否是您的答案,它只是假设所有负值都有 1 个对应的相等正值配对。

SELECT CustomerID, SUM(Stack1.Value) FROM Stack1 
GROUP BY CustomerID

所以结果是:

CustomerID  Value
123456789   200
987654321   210

希望这可以帮助


这个怎么样?

WITH tmpPositive AS (SELECT 
    Stack1.CustomerID, Stack1.Value FROM Stack1 WHERE Stack1.Value > 0),
   tmpNegative AS (SELECT 
    Stack1.CustomerID, Stack1.Value FROM Stack1 WHERE Stack1.Value < 0)
SELECT tmpPositive.CustomerID, MAX(tmpPositive.Value) AS MaxValue FROM tmpPositive
LEFT OUTER JOIN tmpNegative 
ON tmpPositive.CustomerID = tmpNegative.CustomerID AND
   -tmpPositive.Value = tmpNegative.Value
WHERE tmpNegative.CustomerID IS NULL
GROUP BY tmpPositive.CustomerID;

这是测试数据:

CustomerID Value
---------------------
123456789 100
123456789 -100
123456789 300
123456789 -300
123456789 150
123456789 -150
123456789 200
987654321 500
987654321 -500
987654321 200
987654321 -200
987654321 210
123456789 200
123456789 110
987654321 1250

我对上述查询的结果。

CustomerID  MaxValue
--------------------
123456789   200
987654321   1250
于 2013-10-22T09:29:22.160 回答