|
|
Question : SQL sentence with SUM, IF, THEN
|
|
|
|
I have a table with this data ( SELECT * From MyItems )
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
| Value ID Result Payment Date
18,2000 1 Negative 27,0000 04/06/2010
21,0000 1 Positive 9,0000 04/06/2010
14,0000 1 Same 14,0000 04/06/2010
14,0000 2 Negative 26,0000 04/06/2010
10,0000 2 Same 10,0000 04/06/2010
16,5000 2 Same 16,5000 05/06/2010
31,0000 2 Positive 20,0000 05/06/2010
21,0000 2 Same 21,0000 05/06/2010
16,5000 1 Same 16,5000 06/06/2010
20,0000 1 Same 20,0000 06/06/2010
21,0000 3 Same 21,0000 06/06/2010
|
FIRST STEP: I need to group all rows having the same "Date" and same "ID", SUM "value" column and if the "Result" column contains "Negative" it must return "Negative".
example:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
|
18,2000 1 Negative 27,0000 04/06/2010
21,0000 1 Positive 9,0000 04/06/2010
14,0000 1 Same 14,0000 04/06/2010
14,0000 2 Negative 26,0000 04/06/2010
10,0000 2 Same 10,0000 04/06/2010
======== = ===== ==========
53,2000 1 Negative 04/06/2010
24,0000 2 Negative 04/06/2010
|
SECOND STEP: If not exist "Negative" then verify if exist "Positive" and return "positive"
1:
2:
3:
4:
5:
| 16,5000 2 Same 16,5000 05/06/2010
31,0000 2 Positive 20,0000 05/06/2010
21,0000 2 Same 21,0000 05/06/2010
======== = ===== ==========
68,5000 2 Positive 05/06/2010
|
3ยบ STOP if not exist "negative" and "positive" then return "Same". Ejemplo:
1:
2:
3:
4:
5:
6:
7:
8:
|
16,5000 1 Same 16,5000 06/06/2010
20,0000 1 Same 20,0000 06/06/2010
21,0000 3 Same 21,0000 06/06/2010
======== = ===== ==========
37,5000 1 Same 06/06/2010
21,0000 3 Same 06/06/2010
|
And the FINAL RESULT TABLE that I need must be something like that:
1:
2:
3:
4:
5:
6:
7:
|
Result:
53,2000 1 Negative 04/06/2010
24,0000 2 Negative 04/06/2010
68,5000 2 Positive 05/06/2010
57,5000 1 Same 06/06/2010
21,0000 3 Same 06/06/2010
|
Can guys help me doing this with SQL sentences?
Thanks!!! German
|
|
|
|
Answer : SQL sentence with SUM, IF, THEN
|
|
|
|
Try it and tell me if it works.
MIN(Result) will take the minimum of the results.
18,2000 1 Negative 27,0000 04/06/2010 21,0000 1 Positive 9,0000 04/06/2010 14,0000 1 Same 14,0000 04/06/2010
Sorted alphabetically, the Min of (Negative, Postive and Same) is "Negative".
16,5000 2 Same 16,5000 05/06/2010 31,0000 2 Positive 20,0000 05/06/2010 21,0000 2 Same 21,0000 05/06/2010
Sorted alphabetically, the Min of (Positive and Same) is "Positive".
It will work.
|
|
|
|
|