2016-04-21 177 views
-1

我想從日期和時間獲取總和(成本)的數據。我的表字段的數據類型是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 

enter image description here

+1

這看起來太過複雜。爲什麼不有'DATE'字段並做一個簡單的'BETWEEN'? –

+0

這是癡呆。 – Strawberry

回答

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' 
+0

謝謝@selvinsource – JKR

+0

如果我第一次報告生成,我不知道從日期,這意味着2015年12月5日。我運行2015年12月5日之前我需要所有數據的總和 – JKR