2014-04-01 102 views
0

我有3个MySQL表是这样的:连接多个表,条件语句

enter image description here enter image description here

基于该表我想打一个表,条件语句: 如果从表3郭尔> =然后nilai saran =表2中的市长和未成年人,否则saran =表1中值大于0的butuh和bidang的concat。而对于汝=

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

所以,这样的结果:

enter image description here

如何做呢?

+0

这是哪一种语言? – Rahul

+0

语言是mysql – user3440030

+0

不,我的意思是'bidang,kurang,butuh'?从来没有硬这个条款。 – Rahul

回答

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

我一直在尝试这种语法,但结果始终为空。 – user3440030

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中的任何给定的bidang 4非零值,有其中不存在重复值,并且这些值小于或等于4.否则,您将不得不求助于查询中的排名函数。

+0

我试着用那个代码,但是我的代码 – user3440030

+0

纠正了很多错误。这段代码应该让你开始 - 我在mysql语法上有点生疏。如果您认为这绝对没有帮助,请放下笔记,我会删除答案。 – collapsar