Summing up MySQL calculated field where column value is the same
Basically, I am trying to sum up the value of a calculated field when a certain value (in my case COMMUNICATIONS_ID) are equal. These scores are associated with the same COMMUNICATIONS_ID and I want to sum up these values.
开发者_JAVA技巧I am new to SQL and this is my misguided first attempt:
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
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.
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_ID
s, 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
精彩评论