将select语句转换为Group by

时间:2017-11-14 16:06:22

标签: mysql sql

我创建一个视图(见下文) 问题是我获得了公共行,并且使用UNION取消了它们, 我不想使用UNION ALL

所以我的问题是,我怎样才能重写两个"选择..."按表达式分组,分组依据:年份,月份 并获得与UNION ALL

相同的结果
 CREAT VIEW v_test_rerytering (.......) AS
 select
   F.ALDER          
   age,
   cast(P.AR as VARCHAR2(4)) year,  
   ccast((P.MANAD)as VARCHAR2(2)) month,    
   cast(K.KON_KOD as VARCHAR2(50)) SEX,
   cast('Extern' as VARCHAR2(50)) R_KOD,
   F.NR_REK                 
   REK
 from test.Table_anstallda F join test.PERIOD P on P.PERIOD =
 F.PERIOD

 union

 select
   F.ALDER                                   
   age,
   cast(P.AR as VARCHAR2(4)) year,  
   ccast((P.MANAD)as VARCHAR2(2)) month,    
   cast(K.KON_KOD as VARCHAR2(50)) SEX,
  cast('Extern' as VARCHAR2(50)) R_KOD,
  F.NR_dism                
  REK
from test.Table_anstallda F join test.PERIOD P on P.PERIOD_SN =
 F.PERIOD   ;

1 个答案:

答案 0 :(得分:0)

您应该在PERIOD或PERIOD_SN上加入PERIOD,并使用COALESCE或CASE语句设置REK列的字段。

这是合并版本,根据您的数据可能无效:

SELECT F.ALDER age
    ,cast(P.AR AS VARCHAR2(4)) year
    ,ccast((P.MANAD) AS VARCHAR2(2)) month
    ,cast(K.KON_KOD AS VARCHAR2(50)) SEX
    ,cast('Extern' AS VARCHAR2(50)) R_KOD
    ,REK = coalesce(F.NR_REK, F.NR_dism)
FROM test.Table_anstallda F
JOIN test.PERIOD P 
    ON P.PERIOD = F.PERIOD 
    OR p.Period = f.PERIOD_SN