我需要在一个表中显示 MS SQL 数据库中存储的具有 n 个键的键/值对组,每组一条记录,每个键一列。
我找到了这个例子,但在我的例子中,键(最后是列)没有修复,并且也必须来自数据库。 Group key-value columns into a single row
示例:
CREATE TABLE entries
([group_id] int, [attr_key] varchar(20), [attr_value] varchar(20))
;
INSERT INTO entries
([group_id], [attr_key], [attr_value])
VALUES
(1, 'color', 'blue'),
(1, 'size', 'L'),
(2, 'color', 'red'),
(2, 'size', 'M'),
(3, 'color', 'green'),
(3, 'size', 'M'),
(3, 'Vendor', 'myVendor') ,
(3, 'picture', 'Bear')
;
在 fiddle 中测试:http://sqlfiddle.com/#!18/c1ff2/1/0
| group_id | attr_key | attr_value |
|----------|----------|------------|
| 1 | color | blue |
| 1 | size | L |
| 2 | color | red |
| 2 | size | M |
| 3 | color | green |
| 3 | size | M |
| 3 | vendor | myVendor |
| 3 | picture | Bear |
结果应如下所示:
| group_id | color | size | vendor | picture |
|----------|-------|------|----------|---------|
| 1 | blue | L | NULL | NULL |
| 2 | red | M | NULL | NULL |
| 3 | green | M | myVendor | Bear |
当用户稍后添加属性时,表还应该多出一列,而无需更改 SQL 查询。
最佳答案
对于数量不稳定的属性,您应该使用动态数据透视表
declare @columns varchar(max)
declare @sql varchar(max)
set @columns = stuff((select ',' + quotename(attr_key) from entries
group by attr_key
for xml path('')), 1, 1, '')
set @sql = '
select
group_id, ' + @columns + '
from
entries
pivot (
max(attr_value) for attr_key in (' + @columns + ')
) p'
exec (@sql)
关于sql - 将键值列分组为每组一行,每个键列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48823905/