我想从日期和日期获得总和(成本)的数据。我的表字段数据类型是id是INT AUTO INCREMENT,dd是varchar,mm是varchar,yyyy varchar和dd值是01到31,mm值是01到12,年值是4位数年份(2016或2015 ... ) 我想要总和(成本)= 143
SELECT SUM(cost) FROM costing
WHERE
(( dd> CAST('05' AS SIGNED) AND mm= CAST('12' AS SIGNED) AND yyyy= CAST('2015' AS SIGNED))
AND
((dd<= CAST('23' AS SIGNED) AND mm = CAST('01' AS SIGNED) AND yyyy= CAST('2016' AS SIGNED)))
order by id
答案 0 :(得分:1)
您可以像这样使用CAST AS DATE函数:
SELECT
SUM(cost) FROM costing
WHERE
CAST(CONCAT(yyyy,mm,dd) AS DATE) BETWEEN '2015-12-05' AND '2016-01-23'
答案 1 :(得分:1)
首先,您应该考虑您的数据类型。日期不应该在varchar或整数数据类型中。请参阅此http://www.w3schools.com/sql/sql_datatypes.asp
然后你可以在之间使用。请参阅此http://www.w3schools.com/sql/sql_between.asp
然后您的查询中不需要order by id
。
您的查询会喜欢
SELECT SUM(cost) FROM costing WHERE costingdate BETWEEN "5-12-2015" AND 23-1-2015"