Postgresql Postgres中数据的XML元素名称
我在这样的表格中有数据:Postgresql Postgres中数据的XML元素名称,postgresql,Postgresql,我在这样的表格中有数据: ID Date Side Qty 1 2015-07-01 buy 1000 2 2015-07-02 buy 1000 3 2015-07-03 sell 1000 4 2015-07-04 sell 1000 <trades> <buy> <date>2015-07-01</date>
ID Date Side Qty
1 2015-07-01 buy 1000
2 2015-07-02 buy 1000
3 2015-07-03 sell 1000
4 2015-07-04 sell 1000
<trades>
<buy>
<date>2015-07-01</date>
<qty>1000</qty>
</buy>
...
<sell>
<date>2015-07-03</date>
<qty>1000</qty>
</sell>
...
</trades>
我需要以如下格式将其提取为XML:
ID Date Side Qty
1 2015-07-01 buy 1000
2 2015-07-02 buy 1000
3 2015-07-03 sell 1000
4 2015-07-04 sell 1000
<trades>
<buy>
<date>2015-07-01</date>
<qty>1000</qty>
</buy>
...
<sell>
<date>2015-07-03</date>
<qty>1000</qty>
</sell>
...
</trades>
这就产生了
<trades>
<Side>
<date>2015-07-01</date>
<qty>1000</qty>
</Side>
...
<Side>
<date>2015-07-03</date>
<qty>1000</qty>
</Side>
...
</trades>
换句话说,将使用单词Side而不是列的值。在Postgres中是否可以使用数据值作为xml元素名称
我使用的是9.4,不可能对动态标记名使用任何SQL/XML函数。您可以使用格式函数
postgres=# SELECT * FROM foo;
┌──────┬──────┐
│ nm │ val │
╞══════╪══════╡
│ buy │ 100 │
│ sell │ 1000 │
│ buy │ 102 │
│ sell │ 1033 │
└──────┴──────┘
(4 rows)
postgres=# SELECT xmlelement(name "trades", xmlagg(x))
FROM (SELECT format('<%1$s>%2$s</%1$s>',
nm,
xmlagg(xmlelement(name value, val)))::xml x
FROM foo group by nm) s;
┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ xmlelement │
╞═════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╡
│ <trades><sell><value>1000</value><value>1033</value></sell><buy><value>100</value><value>102</value></buy></trades> │
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
(1 row)
谢谢它认为可能是这样。你的解决方案很好。