0

I have two tables (DEP_DEZ & CAR_EXP):

ID  FK_ID_CHESTIONAR    TOTAL_E TOTAL_F TOTAL_STOC
261 644                 87      152     48

ID  MASA_TOTALA FK_ID_CHESTIONAR
405 20          644
406 45          644

if I make an:

SELECT CHT.ID,
       SUM(DEP_DEZ.TOTAL_E+DEP_DEZ.TOTAL_F+DEP_DEZ.TOTAL_STOC)
       FROM CHEST cht
            INNER JOIN DEP_DEZ
               ON DEP_DEZ.FK_ID_CHESTIONAR = CHT.ID
   GROUP BY CHT.ID

The result is 644 and 287 (87+152+48). And it is ok, but if I make:

SELECT CHT.ID,
       SUM(DEP_DEZ.TOTAL_E+DEP_DEZ.TOTAL_F+DEP_DEZ.TOTAL_STOC),
       SUM(CAR_EXP.MASA_TOTALA),
       FROM CHEST cht
            INNER JOIN DEP_DEZ
               ON DEP_DEZ.FK_ID_CHESTIONAR = CHT.ID
            INNER JOIN CAR_EXP
               ON CAR_EXP.FK_ID_CHESTIONAR = CHT.ID
   GROUP BY CHT.ID

the result is 644 and 574 (287*2 - not ok) and 65 (45+20 - ok)

How can I make not to double my "287" in sum?

1 Answer 1

1

You could use multiple SELECT Statements, like this:

SELECT CHT.ID,
   (SELECT SUM(TOTAL_E + TOTAL_F + TOTAL_STOC) 
   FROM DEP_DEZ WHERE FK_ID_CHESTIONAR = cht.ID),
   (SELECT SUM(MASA_TOTALA) FROM CAR_EXP WHERE FK_ID_CHESTIONAR = CHT.ID)
   FROM CHEST cht
GROUP BY CHT.ID
4
  • It works, but what if I want to add SUM(MASA_TOTALA) to SUM(TOTAL_E + TOTAL_F + TOTAL_STOC)?
    – WDrgn
    Aug 20, 2015 at 11:05
  • You can even sum both SELECT. (SELECT1) + (SELECT2). With SELECT1 I'm meaning SUM DEP_DEZ and SELECT2 is SUM CAR_EXP.
    – Niklas B.
    Aug 20, 2015 at 11:09
  • I tried SUM((SELECT SUM(TOTAL_E+TOTAL_F+TOTAL_STOC) FROM DEP_DEZ WHERE FK_ID_CHESTIONAR = CHT.ID)+ (SELECT SUM(MASA_TOTALA) FROM CAR_EXP WHERE FK_ID_CHESTIONAR = CHT.ID)) but it gives me an 704
    – WDrgn
    Aug 20, 2015 at 11:13
  • 1
    (SELECT SUM(TOTAL_E+TOTAL_F+TOTAL_STOC) FROM DEP_DEZ WHERE FK_ID_CHESTIONAR = CHT.ID) + (SELECT SUM(MASA_TOTALA) FROM CAR_EXP WHERE FK_ID_CHESTIONAR = CHT.ID)
    – Niklas B.
    Aug 20, 2015 at 11:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.