SQL:键值:列中的值?
我的表看起来像这样:
+--------------------------+
| key | value-name | value |
+-----+------------+-------+
| 1 | color | green |
| 1 | height | 15 |
| 2 | whatever | lol |
+-----+------------+-------+
我想翻转它,使它看起来像:
+-----+-------+--------+----------+
| key | color | height | whatever |
+-----+-------+--------+----------+
| 1 | green | 15 | --- |
| 2 | --- | --- | lol |
+-----+-------+--------+----------+
使用像这样的sql:
SELECT key AS k,
(SELECT color FROM table WHERE key = k),
(SELECT height FROM table WHERE key = k), ...
... 等等
在不为每个值名称创建子选择的情况下如何完成此操作(因为我相信这不是很快速地) ?
我的DBS是Oracle 10g。
编辑:我后来找到了一些例子,但它们都只是加入,我不能这样做,因为我的表有很多值名称。
my table looks like this:
+--------------------------+
| key | value-name | value |
+-----+------------+-------+
| 1 | color | green |
| 1 | height | 15 |
| 2 | whatever | lol |
+-----+------------+-------+
and i want to flip it so it looks like:
+-----+-------+--------+----------+
| key | color | height | whatever |
+-----+-------+--------+----------+
| 1 | green | 15 | --- |
| 2 | --- | --- | lol |
+-----+-------+--------+----------+
with sql like:
SELECT key AS k,
(SELECT color FROM table WHERE key = k),
(SELECT height FROM table WHERE key = k), ...
... and so on
How can ths be done without creating a subselect for every single value-name (because I believe this is not very fast) ?
My DBS is Oracle 10g.
Edit: I found some examples afterwards, but they all just join and I can't do that because my table has many value-names.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您首先将值作为单独的列获取,这可以使用
case
来完成,然后对键进行分组以将它们放入同一记录中:You would first get the values as separate columns, which you can do with a
case
, then you would group on the key to get them into the same record:使用条件
CASE
语句Use conditional
CASE
statement您可以在此使用 pivot 函数方式:
You can use the pivot function in this way: