简体   繁体   中英

SQL - SUM on similar values based on two conditions

I am stuck trying to write this SQL and receiving this error message

ODBC::Error: 37000 (1003) SQL compilation error: syntax error line 8 at position 8 unexpected 'GROUP'.: Select CASE WHEN forgiven = 0 THEN 6 - SUM(attendance_points) END as total_attendance_p

Goal: Get the sum attendance_points for the same driver_id's if forgiven = 0 and attendance_points in the last 90 days to the current date.

driver_id   attendance_points  forgiven    date
8087956           6                0     2020-02-12
8087956           1                0     2020-02-12
1160725           2                0     2020-02-01
1160725           6                0     2020-02-12
7922706           4                1     2020-02-13    
Select
    CASE WHEN forgiven = 0 THEN 6 - SUM(attendance_points) END as total_attendance_points,
    driver_id,
    date

    FROM attendance_events
    WHERE date < DATEADD("day", -90, current_date());

    GROUP BY 2
  

Use conditional aggregation

Select driver_id,date,
    sum(CASE WHEN forgiven = 0 THEN 6 - attendance_points END ) as total_attendance_points
    FROM attendance_events
    WHERE date < DATEADD("day", -90, current_date())
    group BY driver_id,date

use from below query

select driver_id,sum(attendance_points) from attendance_events where forgiven=0 and date >= DATEADD("day", -90, GETDATE()) group by driver_id

you can see result in photo在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM