我遇到的情况是需要找到为特定日期定义的列的总和。请参阅下表:
在此,我需要找到日期数字的总和,即3月15日至6月15日(在上表中,月份用数字表示,例如5表示五月,依此类推。)
我通过以下查询为每个任务执行了特定月份的操作:
select (d1+d2+d3+d4+d5+d6+d7+d8+d9+d10+d11+d12+d13+d14+d15+d16+d17+d18+d19+d20+d21+d22+d23+d24+d25+d26+d27+d28+d29+d30+d31) as HourSum from table1 where Month='<Given Month>';
我不想查询,但想法只能将一半或更少的列值相加。感谢。
答案 0 :(得分:1)
尝试d1和d2
select sum(d1)+sum(d2) HourSum from table1 group by month,year
参考&#34; group by&#34; https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html
更新回答:
我认为你的表结构非常奇怪,你应该只有一个列名而不是 有31列(d1-d31)。
无论如何,如果要查询2014年3月15日到2014年6月15日的数据,现在考虑相同的表结构和数据,那么您需要编写如下查询: - 总和d1至d31
select sum(d1) +sum(d2) +sum(d3) +sum(d4) +sum(d5) +sum(d6) +sum(d7) +sum(d8)+sum(d9) +sum(d10) +sum(d11) +sum(d12) +sum(d13) +sum(d14) +sum(d15)+sum(d16) +sum(d17) +sum(d18) +sum(d19) +sum(d20)+sum(d21) +sum(d22) +sum(d23) +sum(d24) +sum(d25) +sum(d26) +sum(d27) +sum(d28) +sum(d29)+sum(d30) +sum(d31) as TotalHours
from
(
-- sum 15 march 2014 to 31 march 2014
select 0 as d1,0 as d2,0 as d3, 0 as d5, 0 as d6,0 as d7, 0 as d8,0 as d9,0 as d10,0 as 11,0 as 12,0 as d13,0 as d14,sum(d15) as d15,sum(d16) as d16,sum(d17) as d17,sum(d18) as d18,sum(d19) as d19,sum(d20) as d20,sum(d21) as d21,sum(d22) as d22,sum(d23) as d23,sum(d24) as d24,sum(d25) as d25,sum(d26) as d26,sum(d27) as d27,sum(d28) as d28,sum(d29) as d29,sum(d30) as d30,sum(d31) as d31 from table1 where month = 3 and year=2014 group by Month
)t1
UNION ALL
(
-- sum 1 april 2014 to 31 may 2014
select sum(d1) as d1,sum(d2) as d2,sum(d3) as d3,sum(d4) as d4,sum(d5) as d5,sum(d6) as d6,sum(d7) as d7,sum(d8) as d8,sum(d9) as d9,sum(d10) as d10,sum(d11) as d11,sum(d12) as d12,sum(d13) as d13,sum(d14) as d14,sum(d15),sum(d15) as d15,sum(d16) as d16,sum(d17) as d17,sum(d18) as d18,sum(d19) as d19,sum(d20) as d20,sum(d21) as d21,sum(d22) as d22,sum(d23) as d23,sum(d24) as d24,sum(d25) as d25,sum(d26) as d26,sum(d27) as d27,sum(d28) as d28,sum(d29) as d29,sum(d30) as d30,sum(d31) as d31 from table1 where month in (4,5) and year=2014 group by Month
)t2
UNION ALL
(
-- sum 1 june 2014 to 15 june 2014
select sum(d1) as d1,sum(d2) as d2,sum(d3) as d3,sum(d4) as d4,sum(d5) as d5,sum(d6) as d6,sum(d7) as d7,sum(d8) as d8,sum(d9) as d9,sum(d10) as d10,sum(d11) as d11,sum(d12) as d12,sum(d13) as d13,sum(d14) as d14,sum(d15),sum(d15) as d15, 0 as d16,0 as d17, 0 as d18,0 as d19, 0 as d20, 0 as d21, 0 as d22,0 as d23,0 as d24,0 aS d25,0 AS d26,0 as d27,0 as d28,0 as d29,0 as 30,0 as 31 from table1 where month = 6 and year=2014 group by Month
)t3
再次,如果可能的话,改变你的表结构..