简体   繁体   中英

SQL, sum in column(s) based on date column

I had a long break from SQL and am a bit rusty. Let's say I have 3 columns in my table: username, value_of_sale, date.

I need a select statement to show me 4 columns based on this table:

username
sum of value_of_sales (where date = today)
sum of value_of_sales (where date = today-1)
sum of value_of_sales (where date = today-2)

I am using db2.

Without trying to merge all three of those together, it's very simple to do them individually:

Today:

SELECT username, SUM(value_of_sale) FROM `tableName` WHERE DATE(`date`) = CURDATE() GROUP BY username

Yesterday:

SELECT username, SUM(value_of_sale) FROM `tableName` WHERE DATE(`date`) = DATE_ADD(CURDATE(), INTERVAL -1 DAY) GROUP BY username

Two Days Ago:

SELECT username, SUM(value_of_sale) FROM `tableName` WHERE DATE(`date`) = DATE_ADD(CURDATE(), INTERVAL -2 DAY) GROUP BY username

DATE('date') takes the date portion of the timestamp. If your data is just listed in dates, then you can just compare 'date' to today's date.

CURDATE() gets today's date in the server.

DATE_ADD() is used to add or subtract days.

Use SUM and GROUP BY .

SELECT username,
(CASE WHEN date = CURRENT_DATE THEN value_of_sale ELSE 0 END) AS SUMtoday,
(CASE WHEN date = DAYOFYEAR(CURRENT_DATE) - 1 ) THEN value_of_sale ELSE 0 END) AS SUMtoday-1,
(CASE WHEN date = DAYOFYEAR(CURRENT_DATE) - 2 ) THEN value_of_sale ELSE 0 END) AS SUMtoday-2
FROM yourtable
GROUP BY username
I have three fields in my table id,sale_amount,created_at(Sales Date)    

SELECT (SELECT sum(sale_amount) FROM `sales` WHERE created_at = 
CURDATE()) AS todaySale,(SELECT sum(sale_amount) FROM `sales` WHERE 
created_at = CURDATE() -1) AS YesterdaySale,(SELECT sum(sale_amount) 
FROM `sales` WHERE created_at = CURDATE() - 2) AS Last2DaysSale

This will help you for sure. Thank You

Probably not the most efficient method, but ...

select username, 
sum(case when date = today then value_of_sales else 0 end) [Today],
sum(case when date = today-1 then value_of_sales else 0 end) [Yesterday],
sum(case when date = today-2 then value_of_sales else 0 end) [TheDayBefore]
from table
group by username

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