2016-02-03 58 views
-1
Select SUM(Breakfast) FROM `expense` WHERE MONTHNAME(Date)='February' 

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

合併結果取決於條件。查詢合併兩個結果取決於條件

  1. SUM(Breakfast)如果是2月份,應該選擇。

如果不是意味着

  • (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

    的MySQL或SQL Server?你已經標記了他們兩個。 – Fred

    +0

    不知道問題是什麼。 – shawnt00

    回答

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

    謝謝它的工作精細 –

    +0

    @AmareshHD歡迎 –

    +0

    這很有可能是一個'case'表達式比union更快。 – shawnt00