如何从两个表中选择数据

时间:2015-01-07 08:36:30

标签: sql postgresql select union-all

我从相同的表中选择了两个不同的数据,但我需要将这两个不同的数据合并为一个表作为select。

例如,我有这个:

SELECT DISTINCT db.nazev, db.skupina, db.datum_od1, db.datum_do1, db.mnozstvi, db.cena_bez_dph, db.datum_od, db.datum_do2, db.mnozstvi2, db.cena_bez_dph2 
FROM (
SELECT s.nazev as nazev, s.kod as skupina, (select (DATE '<<datum_od1>>')) as datum_od1, (select (DATE '<<datum_do1>>')) as datum_do1,  sum(f.mnozmj) as mnozstvi, sum(f.sumZkl) as cena_bez_dph FROM dpolfak as f
LEFT OUTER JOIN ddoklfak hla ON hla.iddoklfak = f.iddoklfak
LEFT OUTER JOIN ccenik c ON c.kod = f.kod
LEFT OUTER JOIN cskupzboz s ON s.idskupzboz = c.idskupzboz
where f.modul = 'FAV' and f.datvyst >= '<<datum_od1>>' and f.datvyst <= '<<datum_do1>>'
GROUP BY s.nazev, s.kod
UNION ALL
SELECT s.nazev as nazev, s.kod as skupina, (select (DATE '<<datum_od2>>')) as datum_od2, (select (DATE '<<datum_do2>>')) as datum_do2,  sum(f.mnozmj) as mnozstvi2, sum(f.sumZkl) as cena_bez_dph2 FROM dpolfak as f
LEFT OUTER JOIN ddoklfak hla ON hla.iddoklfak = f.iddoklfak
LEFT OUTER JOIN ccenik c ON c.kod = f.kod
LEFT OUTER JOIN cskupzboz s ON s.idskupzboz = c.idskupzboz
where f.modul = 'FAV' and f.datvyst >= '<<datum_od2>>' and f.datvyst <= '<<datum_do2>>'
GROUP BY s.nazev, s.kod
) db

但问题是功能“UNION ALL”将所有数据合并为一个,但我需要从表2中选择不同的数据到新列中,你可以在主要选择中看到它。

主要的问题是,这不能使用函数union all来执行“db.datum_do2,db.mnozstvi2,db.cena_bez_dph2”(它仍然写信给我该列不存在)。我该如何解决?

这是我的实际结果:

nazev                   skupina   Datum       Datum        Množství Cena bez DPH
Směsi éterických olejů | SL024 | 01.12.2014 | 19.12.2014 | 1 798,00 | 208 142,79

Směsi éterických olejů | SL024 | 20.11.2014 | 07.01.2015 | 662,00   | 86 374,52

我想要这个:

nazev                   skupina   Datum       Datum        Množství Cena bez DPH  Datum 2      Datum 2       Množství 2  Cena bez DPH 2
Směsi éterických olejů | SL024 | 01.12.2014 | 19.12.2014 | 1 798,00 | 208 142,79 |20.11.2014 | 07.01.2015 | 662,00   | 86 374,52

1 个答案:

答案 0 :(得分:1)

如果你真的想要将UNION ALL的不同查询列分开,你可以这样做:

select col1, case when q = 1 then colA end, case when q = 2 then colA end,...
(select col1, colA as colA, 1 as q
 from...
 union all
 select col1, colB as colA, 2 as q
 from...
) db

select col1, col2 etc
(select col1, colA, null from...
 UNIOM ALL
 select col1, null, colB from...)