如何自我加入条件并在前面添加一列?

时间:2018-12-18 12:52:45

标签: sql postgresql

我有这个查询

SELECT
   "os_bulan_lalu",
   "os_update"
FROM (
        SELECT
   (SELECT "OUTSTANDING" FROM tbl_nominatif_hasil 
        WHERE "BUSS_DATE"='2018-11-30' AND "COLLDET"='1') 
        as os_bulan_lalu,
   (SELECT "OUTSTANDING" FROM tbl_nominatif_hasil 
        WHERE "BUSS_DATE"='2018-12-17' AND "COLLDET"='2A')
        as os_update
   ) AS temp

但是当我跑步并且我想要

这样的结果时此查询是错误的
os_bulan_lalu | os_update

      232323 | 21424
      343242 | 432
       23432 | 23432
      234324 | 234324
      234324 | 23423423

我的意思是os_bulan_lalu是BUSS_DATE"='2018-11-30' AND "COLLDET"='1'的地方,而os_update是"BUSS_DATE"='2018-12-17' AND "COLLDET"='2A'

错误是

  

[Err]错误:用作表达式的子查询返回的一行以上

我想要类似的结果

os_bulan_lalu | os_update

      232323 | 21424
      343242 | 432
       23432 | 23432
      234324 | 234324
      234324 | 23423423

1 个答案:

答案 0 :(得分:0)

也许这样的事情可能有用

SELECT A.OUTSTANDINGAS os_bulan_lalu, B.OUTSTANDINGAS os_update 
FROM (SELECT OUTSTANDING, ROW_NUMBER() OVER ( ORDER BY OUTSTANDING) AS row_num 
      FROM tbl_nominatif_hasil 
      WHERE BUSS_DATE = '2018-11-30' AND COLLDET = '1') AS A
JOIN (SELECT OUTSTANDING, ROW_NUMBER() OVER ( ORDER BY OUTSTANDING) as row_num 
      FROM tbl_nominatif_hasil 
      WHERE BUSS_DATE = '2018-12-17' AND COLLDET = '2A') AS B ON A.row_num = B.row_num

它假设两个查询的行数相等,但是如果不了解输入内容,就很难给出更好的答案。

更新如果子查询返回不同的行数,则最好执行FULL OUTER JOIN而不是JOIN