【问题标题】:more than one row returned by a subquery used as an expression postgresql由用作表达式 postgresql 的子查询返回的多行
【发布时间】:2013-05-24 11:18:47
【问题描述】:

postgresql,我有一个表 my_table 4 表,其中包含列 stxstxid、stxuserid sumamountstx、userid、amountcredit、amountrc 我的目标是将具有相同 stxstxid 的不同行合并为一行,同时将这些选定行的销售列汇总到合并行中。

例如

stx                              stxitem    
stxid   stxuserid                stxid  amountstx
-------------------            -----------------------
001           A                 001            20
002           B                 002            12
002           B                 002            200
003           C                 003            360
003           C                 003            400
004           D                 004            300
004           D                 004            450
004           D                 004            100
005           E                 005            800
005           E                 005            950
005           E                 005            800
005           E                 005            600

srcitem         
srcid   userid  soueceid  amountsrc 
------------------------------------
A0001   src001    001       20
A0002   src002    002       212
A0003   src003    003       500
A0004   src004    004       800


credit      
creditID     stxid     amountcredit
---------------------------------------
9X0001        001         0
9X0002        002         0
9X0003        003        60
9X0004        004        50
9X0005        005        3150

这是我应该得到的

结果

stxid   stxuserid   sumamountstx    userid  amountcredit    amountsrc
---------------------------------------------------------------------------
003           C           760        src003     60              500
005           E           3150                  3150

我做了一些研究,发现 self join 应该做一些类似于我应该得到的事情。

【问题讨论】:

  • 我看到stx (stxid)stxitem (stxid)credit (stxid) 之间的关系。 srcitem 中没有 stxid 列,但输出中需要来自 srcitem 的列。嗯?我们是否应该假设列srcitem.souceid 是其他表的键?

标签: sql postgresql select sum subquery


【解决方案1】:
select
 a.stxid,
 a.stxuserid,
 x.sumamountstx,
 s.userid,
 s.amountsrc
from
 (select stxid, stxuserid from stx group by stxid, stxuserid) a
 join (select stxid, sum(amountstx) sumamountstx from stxitem group by stxid) x using (stxid)
 join credit using (stxid)
 left join srcitem s on (a.stxid = s.souceid)

不确定这是否正确。给我们sqlfiddle的样本数据,我们可以测试。

【讨论】:

  • 谢谢 twn08。但 stxitem 不是总和。
  • 对不起,我不明白你的意思。 stxitem 是一个表,在我的查询中有sum(stxitem.amountstx)。请给我们关于 sqlfiddle 的示例数据。
  • 不过要试试。稍后再查找总费用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-06
  • 2018-02-13
相关资源
最近更新 更多