查询结合两个结果取决于条件

时间:2016-02-03 18:24:30

标签: mysql sql

Select SUM(Breakfast) FROM `expense` WHERE MONTHNAME(Date)='February'

Select (BreakFast+lunch+dinner) as Total FROM `expense` WHERE Date='2016-01-01'

综合结果取决于条件。

    如果是2月份,则应选择
  1. SUM(Breakfast)
  2. 如果不是意味着

    1. (BreakFast+lunch+dinner) as Total必须在特定的日期出现。
    2. 我试过联盟但我没有得到理想的结果

      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)
                 --------------------------
      

1 个答案:

答案 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`