0

基本上,当某个值(在我的情况下为 COMMUNICATIONS_ID)相等时,我试图总结计算字段的值。这些分数与相同的 COMMUNICATIONS_ID 相关联,我想总结这些值。

我是 SQL 新手,这是我被误导的第一次尝试:

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
4

2 回答 2

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

我认为不需要在这里将表加入到自身中。

于 2011-01-26T22:36:50.177 回答
1

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
于 2011-01-26T22:32:15.947 回答