Gabriele Cozzolino
Gabriele Cozzolino

Reputation: 194

SQL aggregation query and sum columns

I have this table (I put the name over needed colums)

iddip         date                 idv idc  val
47    2018-06-01 00:00:00.000   0   3   3   60  NULL    NULL
47    2018-06-01 00:00:00.000   0   1   3   200 NULL    NULL
47    2018-06-01 00:00:00.000   0   1   4   280 NULL    NULL
43    2018-06-01 00:00:00.000   0   3   2   510 NULL    NULL
53    2018-06-01 00:00:00.000   0   1   4   480 NULL    NULL
29    2018-06-01 00:00:00.000   0   3   2   510 NULL    NULL
2     2018-06-11 00:00:00.000   0   1   2   480 NULL    NULL
47    2018-06-02 00:00:00.000   0   1   3   100 NULL    NULL

I want to obtain this:

id idc Totidv1 Totidv3 TOT
47   3     300     60  360
47   4     280      0  280
43   2       0    510  510
53   4     480      0  480
29   2       0    510  510
2    2     480      0  480

The closest I can get is:

 SELECT DISTINCT(iddip),IDCENTROCOSTO,tot=SUM(VALORE),ord=( SELECT SUM(isnull(VALORE,0)) FROM VALORIVOCICDC WHERE IDVOCE='1' and iddip=v.IDDIP and IDCENTROCOSTO ='3' GROUP BY iddip,IDCENTROCOSTO),
  str=( SELECT SUM(isnull(VALORE,0)) FROM VALORIVOCICDC WHERE IDVOCE='3' and iddip=v.IDDIP and IDCENTROCOSTO ='3' GROUP BY iddip,IDCENTROCOSTO)
FROM VALORIVOCICDC v
GROUP BY v.iddip,IDCENTROCOSTO

But it returns wrong sums in totidv1 and totisv3, How can I do this? Thanks for any hint

Upvotes: 0

Views: 30

Answers (1)

JNevill
JNevill

Reputation: 50200

You just need a GROUP BY here (not distinct) and a couple of CASE statements:

SELECT
    id,
    idc,
    SUM(CASE WHEN idv=3 THEN idv ELSE 0 END) as totidv1,
    SUM(CASE WHEN idv=1 THEN idv ELSE 0 END) as totidv3,
    SUM(idv) as Tot
FROM yourtable
GROUP BY id, idc

Note that Distinct is not a function that you can call like SELECT DISTINCT(somecolumn) This is functionally equivalent to SELECT DISTINCT somecolumn... in that it works against the entire record set returned by the SELECT statement either way.

Upvotes: 1

Related Questions