Select SUM(Breakfast) FROM `expense` WHERE MONTHNAME(Date)='February'
Select (BreakFast+lunch+dinner) as Total FROM `expense` WHERE Date='2016-01-01'
综合结果取决于条件。
SUM(Breakfast)
。如果不是意味着
(BreakFast+lunch+dinner) as Total
必须在特定的日期出现。我试过联盟但我没有得到理想的结果
Table expense
--------------
Date Breakfast Lunch Dinner
2016-02-02 20 20 30
2016-02-03 30 30 20
2016-01-02 40 30 20 90(If It is a month Of Not a Feb)
50(If It is a month Of Feb)
--------------------------
答案 0 :(得分:1)
使用Union ALL:
Select SUM(Breakfast) as Total FROM `expense` WHERE month(Date)=2
union all
Select Sum(BreakFast)+sum(lunch)+sum(dinner) as Total FROM `expense` WHERE month(Date)<>2
使用案例(最快的选择):
SELECT CASE
WHEN MONTH(DATE)=2 THEN SUM(Breakfast)
WHEN MONTH(DATE)<>2 THEN SUM(BreakFast)+SUM(lunch)+SUM(dinner)
ELSE 0 END
AS Total FROM `expense`