如何不是从主交易表而是从明细表连接项目

时间:2019-01-19 12:55:30

标签: sql sql-server tsql group-by string-aggregation

我有交易表proposal_header,明细表是proposal_item,我需要的是在tender_number中由detail_number分组的proposal_item串联,但是我不知道如何连接它,查询应该如何?

proposal_header表为:

id  tender_number
7   BS7
12  BS12
14  CS14

proposal_item表为:

proposal_header_id  detail_number
  7                161932
  7                161929
  12               161932
  12               161929
  14               334659

然后我加入了:

select b.id as mainId,a.detail_number ,b.tender_number
from dbo.proposal_header b
inner join dbo.proposal_item a on a.proposal_header_id =b.id

加入的结果是:

main Id  detail_number  tender_number
7        161932         BS7
7        161929         BS7
12       161932         BS12
12       161929         BS12
14       334659         CS14 

但我需要的只是详细编号和连接招标编号, 有解决方案可以做到这样吗?

detail_number  tender_number
161932          BS7, BS12
161929          BS7, BS12
334659          CS14 

2 个答案:

答案 0 :(得分:0)

您将需要使用聚合查询以及字符串聚合功能。实际功能取决于您的RDBMS:

  • oracle:LISTAGG
  • mysql:GROUP_CONCAT
  • sql-server> = 2017:STRING_AGG
  • postgres:STRING_AGG

以下是mysql的示例:

select 
    a.detail_number,
    group_concat(
        b.tender_number
        order by b.tender_number separator ', '
    ) as tender_numbers
from 
    dbo.proposal_header b
    inner join dbo.proposal_item a 
        on a.proposal_header_id =b.id
group by a.detail_number

使用sql-server <2017:

SELECT
    pi.detail_number,
    tender_numbers = STUFF(
        (
            SELECT ',' + ph.tender_number
            FROM dbo.dbo.proposal_header AS ph
            WHERE ph.id = pi.proposal_header_id
            ORDER BY ph.tender_number
        ).value('.', 'varchar(max)'),
        1, 
        1,
        ''
    )
FROM dbo.proposal_item AS pi
GROUP BY pi.detail_number

答案 1 :(得分:0)

不幸的是,在SQL Server 2012中,您必须使用变通办法。最好的SO线程是这样的:

https://stackoverflow.com/a/31212041/27876