2016-11-17 94 views
0

我創建一個sql查詢通過從表單字段中獲取某些變量。但有些地區彼此重複。所以這打破了MySQL的案例結構。舉個例子:Mysql案例問題

(case 
    when `field` IN (1,2) then 'area 1' 
    when `field` = 3 then 'area 2' 
    when `field` = 4 then 'area 3' 
    when `field` IN (1,2,3,4) then 'area 4' 
end) as cases 

Group by cases 

我知道「區域4」永遠不會在結果中顯示,但有一種方式來展現?

sqlfiddle

回答

0

通過優先級排序。首先是最匹配的查詢,然後是較小的查詢。

就像是:

(case 
    when `field` IN (1,2,3,4) then 'area 4' 
    when `field` IN (1,2) then 'area 1' 
    when `field` = 3 then 'area 2' 
    when `field` = 4 then 'area 3' 
end) as cases 
+0

但後來我剛開始的「結果查詢區域4'。我想查看所有情況 –

+0

鏈接到sqlfiddle不加載 – user2693928

+0

我編輯鏈接http://sqlfiddle.com/#!9/9307b6/1 –

0

關於你SQLfiddle

下面是我能想出

SELECT ROUND(SUM(quantity)/1000) as `quantity`, 
ROUND(SUM(value)/1000) as `value`, 
(case 
    when istpoz REGEXP '^(7207|7218|7224|7206)' 
    then 
    case when istpoz REGEXP '^(7206|7207)' 
     then 'Yarı Mamul (Alaşımsız)' else 'Yarı Mamul (Tamamı)' end 
    else 
    case 
     when istpoz REGEXP '^(7224)' then 'Yarı Mamul (Alaşımlı Çelik)' 
     when istpoz REGEXP '^(7218)' then 'Yarı Mamul (Paslanmaz Ç.)' 
    end 
end) as istpozz, 
`year` FROM 
export as x WHERE 
`year` IN (2016) 
AND `month` IN (1,2,3,4) 
AND `country_id` IN (1) 
AND `istpoz` REGEXP '^(7206|7207|7224|7218)' GROUP BY istpozz,year