我正在編寫一個存儲過程,它將根據酒類和工作號顯示是/否計數。我開始通過工會來編程當前的類別 - 葡萄酒,啤酒,威士忌 - 但除此之外,可能會有更多的類別,並且我將這些代碼視爲體積龐大。是否可以在一個循環中執行一個聯合,然後傳遞酒精類別參數?託運互聯網,並看到很少關於這個問題,所以任何幫助或指導將不勝感激。在Union中循環全部
我的代碼的開始...
delimiter $$
create procedure alc_cat_yn (in jid int)
begin
select
cast(concat(jobid,' - Wine')
as char(50)) as `Job Number - Consumed Yesterday`
,sum(case when wine_id=1 then 1 else 0 end) as y
,sum(case when wine_id=2 then 1 else 0 end) as n
from demos
where jobid=jid
group by jobid
union all
select
cast(concat(jobid,' - Beer')
as char(50)) as `Job Number - Consumed Yesterday`
,sum(case when beer_id=1 then 1 else 0 end) as y
,sum(case when beer_id=2 then 1 else 0 end) as n
from demos
where jobid=jid
group by jobid
union all
select
cast(concat(jobid,' - Whisky')
as char(50)) as `Job Number - Consumed Yesterday`
,sum(case when whisky_id=1 then 1 else 0 end) as y
,sum(case when whisky_id=2 then 1 else 0 end) as n
from demos
where jobid=jid
group by jobid;
end
您在這裏遇到困難的原因是您的模式未正確歸一化。 'demos'表中不應該有特定的'wine_id','beer_id'和'whisky_id'列。你在工作和酒精類別之間有多對多的關係,你可以通過互聯網尋找技術來正確標準化。 –