使用条件语句连接多个表

时间:2014-04-01 13:26:59

标签: mysql sql

我有3个像这样的mysql表:

enter image description here enter image description here

基于该表我想用条件语句创建一个表: 如果skor来自表3> = nilai然后saran = mayor和minor来自table2,则saran = butuh来自表1,其值大于0并且由bidang连接。而对于nilai =

selct((max(skor)-min(skor))*0.25)+min(skor) from table 3

所以,结果如下:

enter image description here

如何制作这个?

2 个答案:

答案 0 :(得分:0)

尝试以下查询:

select
NIP,
Bidang,
case when Skor >= ((max(skor)-min(skor))*0.25)+min(skor)
then concat(mayor,',',minor) 
else concat(Butuh,',',Bidang)
end  as Saran
from
(
select table2.*,
table1.Butuh,
table1.Kurang,
table3.Skor
from table2 join table1
on table2.Bidang = table1.Bidang
left join table3 
on table2.NIP = table3.NIP
where table1.Butuh > 0
) tab

答案 1 :(得分:0)

假设nilai仅表示全局评分阈值,您基本上必须...

  • 构建一个汇总nilai
  • 的查询
  • 将来自不同记录的数据汇总为单个字符串
  • 加入表格和汇总查询
  • 选择所需数据,根据需要应用函数创建正确的输出。

您的结果将如下所示:

select t2.Nip
     , t3.bidang
     , case when t3.skor >= t3disc.nilai then t2.mayor || ', ' || t2.minor else base_1.butuh_agg end
                    saran
  from table_2 t2
  join table_3 t3   on ( t3.Nip = t2.Nip and  t3.bidang = t2.bidang )
  join (
                select t11.bidang
                     , t11.butuh
                        || CASE WHEN t12.butuh IS NOT NULL THEN ', ' || t12.butuh ELSE '' END 
                        || CASE WHEN t13.butuh IS NOT NULL THEN ', ' || t13.butuh ELSE '' END 
                        || CASE WHEN t14.butuh IS NOT NULL THEN ', ' || t14.butuh ELSE '' END 
                        || CASE WHEN t15.butuh IS NOT NULL THEN ', ' || t15.butuh ELSE '' END 
                            butuh_agg
                  from (
                            select t1.bidang
                                 , min(t1.kurang)   kmin
                              from table_1  t1
                          group by t1.bidang
                       ) t11
             left join table_1  t12 on ( t12.bidang = t11.bidang AND t12.kurang = t11.kmin + 1)
             left join table_1  t13 on ( t13.bidang = t11.bidang AND t13.kurang = t11.kmin + 2)
             left join table_1  t14 on ( t14.bidang = t11.bidang AND t14.kurang = t11.kmin + 3)
             left join table_1  t15 on ( t15.bidang = t11.bidang AND t15.kurang = t11.kmin + 4)
        ) base_1   on ( base_1.bidang = t2.bidang )
   join (
               select t31.bidang
                    , t3agg.nilai
                 from table_3  t31
           cross join (
                         select (max(t32.skor) - min(t32.skor)) * 0.25 ) + min(t32.skor)   nilai
                           from table_3 t32
                      ) t3agg
        ) t3disc  on ( t3disc.bidang = t2.bidang )
      ;

此建议假设表1中任何给定的双边最多有4个非零值,这些值之间没有重复,并且这些值小于或等于4.否则您必须在您的查询中使用排名功能。