SQL,基于日期列的列中的总和

时间:2017-09-18 13:23:07

标签: sql db2

我与SQL有很长的休息时间并且有点生疏。我们说我的表中有3列:username,value_of_sale,date。

我需要一个select语句来显示基于此表的4列:

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)

我正在使用db2。

4 个答案:

答案 0 :(得分:1)

不试图将所有这三者合并在一起,单独完成它们非常简单:

今天:

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

昨天:

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

前两天:

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

DATE('date')获取时间戳的日期部分。如果您的数据仅列在日期中,那么您只需比较日期'到今天的约会。

CURDATE()今天在服务器中获取日期。

DATE_ADD()用于添加或减去天数。

答案 1 :(得分:1)

使用SUMGROUP 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

答案 2 :(得分:1)

def initialize_properly():
    W = tf.Variable(10)
    with tf.Session() as sess:
        #This way
        tf.global_variables_initializer().run()

        print(W.eval()) 
        print(sess.run(W))

这将对您有所帮助。谢谢

答案 3 :(得分:1)

可能不是最有效的方法,但是......

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