我有一个Stored proc以大致这种格式返回数据
ID | Field1 | Field2 | Group | Description
------------------------------------------------
1 | A | A | g1 | g1A description
1 | A | A | g2 | g2A description
2 | B | B | g1 | g1B description
2 | B | B | g2 | g2B description
3 | C | C | g1 | g1C description
3 | C | C | g2 | g2C description
SELECT
a.ID,
a.Field1,
b.Field2,
c.Group,
c.Description
FROM A as a
INNER JOIN B b ...
INNER JOIN C c ...
在代码中,我将数据集转换为JSON
[
{
ID: 1,
Field1: A,
Field2: A,
Groups: {
g1: g1A description,
g2: g2A description,
}
}, {
ID: 2,
Field1: B,
Field2: B,
Groups: {
g1: g1B description,
g2: g2B description,
}
}, {
ID: 1,
Field1: C,
Field2: C,
Groups: {
g1: g1C description,
g2: g2C description,
}
}
]
我不喜欢该过程主要返回每行中的重复数据。我是否可以通过某种方式在SQL中执行分组,以便返回的数据集类似于
ID | Field1 | Field2 | Groups
------------------------------------------------
1 | A | A | 'Groups: { g1: g1A description, g2: g2A description }'
2 | B | B | 'Groups: { g1: g1B description, g2: g2B description }'
3 | C | C | 'Groups: { g1: g1C description, g2: g2C description }'
要么
ID | Field1 | Field2 | g1 | g2
----------------------------------------------------------
1 | A | A | g1A description | g2A description
2 | B | B | g1B description | g2B description
3 | C | C | g1C description | g2C description
使用'D-Shih的答案,我想出了这个:
SELECT
a.ID,
a.Field1,
b.Field2,
(
SELECT
MAX(CASE WHEN [Group] = 'g1' THEN Description END) g1,
MAX(CASE WHEN [Group] = 'g2' THEN Description END) g2
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
) as Groups
FROM A as a
INNER JOIN B b ...
INNER JOIN C c ...
ID | Field1 | Field2 | Groups
------------------------------------------------
1 | A | A | '{ "g1": "g1A description", "g2": "g2A description" }'
2 | B | B | '{ "g1": "g1B description", "g2": "g2B description" }'
3 | C | C | '{ "g1": "g1C description", "g2": "g2C description" }'
https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=4bf8a009fe91bbbd0f3246723a1f9eb4
你的第二个期望结果可以使用条件聚合函数来实现它。
SELECT ID,
Field1,
Field2,
MAX(CASE WHEN [Group] = 'g1' THEN Description END) g1,
MAX(CASE WHEN [Group] = 'g2' THEN Description END) g2
FROM T
GROUP BY ID,Field1,Field2
注意
T
是您当前的结果。