我希望在一行中有相同id的行数据

5tmbdcev  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(378)

表格格式如下

ID | MID | PID |   Quantity
1  |  1  |   2 |      3
2  |  1  |   3 |     10
3  |  2  |   2 |     11
4  |  2  |   1 |      5

我想得出如下结果

ID | MID |     Final
1  |  1  |   2(3),3(10)
2  |  2  |   2(11),1(5)
k2arahey

k2arahey1#

第一 concate 两列然后做 string_agg . 这是演示。

with cte as
(
  select
    mid,
    concat(pid, '(', quantity, ')') as concat_col
  from table1
)

select
  row_number() over (order by mid) as id,
  mid,
  string_agg(concat_col, ', ') as final
from cte
group by
  mid

输出:

| id  | mid | final       |
| --- | --- | ----------- |
| 1   | 1   | 2(3), 3(10) |
| 2   | 2   | 2(11), 1(5) |

如果您使用的是旧版本的sql server,请尝试以下操作

with cte as
(
  select
    mid,
    concat(pid, '(', quantity, ')') as concat_col
  from table1
)

select
  row_number() over (order by mid) as id,
  mid,
  stuff((
  select ',' + concat_col
  from cte c1
  where c.mid = c1.mid
  for XML PATH('')
  ), 1, 1, '') as final
from cte c
group by
  mid
omvjsjqw

omvjsjqw2#

select MID, string_agg(concat(PID, '(', Quantity,')'), ', ')
    from dbo.Sample 
    group by MID

Result : 
    MID FINAL
    1   2(3), 3(10)
    2   2(11), 1(5)

相关问题