Question

En gros, j'essaie de résumer la valeur d'un champ calculé quand une certaine valeur (dans mon cas COMMUNICATIONS_ID) sont égaux. Ces scores sont associés à la même COMMUNICATIONS_ID et je veux résumer ces valeurs.

Je suis nouveau à SQL et c'est ma première tentative malencontreuse:

SELECT *
FROM consumer_action_log as cal1
JOIN consumer_action_log as cal2
    ON cal1.COMMUNICATIONS_ID=cal2.COMMUNICATIONS_ID
    AND cal1.COMM_TYPE_ID=4
Était-ce utile?

La solution

SELECT COMMUNICATIONS_ID, SUM(fieldName) 
FROM consumer_action_log
WHERE COMM_TYPE_ID = 4
GROUP BY COMMUNICATIONS_ID

I don't see a need to JOIN the table to itself here.

Autres conseils

It may be better to split the ON and WHERE conditions, even if the result is the same for INNER JOINs. Makes it clearer what links the two tables.

SELECT sum(cal2.somecolumn)
FROM consumer_action_log as cal1
JOIN consumer_action_log as cal2
    ON cal1.COMMUNICATIONS_ID=cal2.COMMUNICATIONS_ID
WHERE cal1.COMM_TYPE_ID=4
  • Find cal1 records where COMM_TYPE_ID=4
  • Join to cal2 (self join) where the COMMUNICATIONS_ID is equal to cal1
  • Sum up some column from cal2

If the filter on COMMS_TYPE_ID=4 results in multiple cal1.COMMUNICATIONS_IDs, then you will want to GROUP BY COMMUNICATIONS_ID (doesn't matter from cal1 or cal2 - they are the same)

SELECT cal2.COMMUNICATIONS_ID, sum(cal2.somecolumn)
FROM consumer_action_log as cal1
JOIN consumer_action_log as cal2
    ON cal1.COMMUNICATIONS_ID=cal2.COMMUNICATIONS_ID
WHERE cal1.COMM_TYPE_ID=4
GROUP BY cal2.COMMUNICATIONS_ID
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top