简体   繁体   中英

Mysql query Sum with Case

I have two tables.

One contains default data for 3 columns, (value is 1 or 0) In the same table is a ClientID

Another table contains edited data with a date, ClientID and a extra column named 'Changed'

If Changed = 1 then the values in the 3 columns are changed and therefore need to be read from the second table.

This al works fine, but I want to make a report in php where a daterange can be selected and a query should group by ClientID and count all 1's in the selected daterange of the 3 columns. (Each column seperate)

Here's the trick: When Changed = 0 in the specific row then It should check the default value and if Changed = 1 it should check the second table. And then count it with the previous rows.

I hope you understand what I want to create

You can use IF function from SQL

For example

SELECT SUM(IF(Changed=1, t1.col1, t2.col2)) FROM t1, t2 WHERE t1.id=t2.id

This is example how you can use columns for case in SUM

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