[英]Oracle SQL — Grabbing values from multiple rows
I have a table like this: 我有一张这样的桌子:
TABLE: FACTS
ID KEY VALUE
1 name Jeremy
1 height 5'11
1 awesomeness 10
2 name Mark
2 awesomeness 4
3 height 4'6
So, the (ID,KEY) tuple can be considered as a primary key. 因此,(ID,KEY)元组可以视为主键。
I am trying to return rows like this: 我试图返回这样的行:
ID NAME HEIGHT AWESOMENESS
1 Jeremy 5'11 10
2 Mark (null) 4
3 (null) 4'6 (null)
So other than by doing a sub-select for each column, how can grab the key values, if they are there, and collect them into my single row? 因此,除了通过对每一列进行子选择之外,如何抓住键值(如果有)并将它们收集到我的单行中? What I tried so far was:
到目前为止,我尝试过的是:
SELECT
id,
CASE WHEN facts.key = 'name' THEN value END name,
CASE WHEN facts.key = 'height' THEN value END height,
CASE when facts.key = 'awesomeness' THEN value END awesomeness
FROM
facts
WHERE
facts.id in (1,2,3)
But for obvious reasons this returns one row per key that matches, not one row per id. 但是出于明显的原因,这会向每个匹配的键返回一行,而不是每个id返回一行。
How can I go about getting this the way I want? 我该如何以自己想要的方式进行操作?
Thanks! 谢谢!
You can pivot the data like this in any version of Oracle. 您可以在任何版本的Oracle中旋转这样的数据。
SELECT id,
MAX( CASE WHEN key = 'name' THEN value ELSE null END ) name,
MAX( CASE WHEN key = 'height' THEN value ELSE null END ) height,
MAX( CASE WHEN key = 'awesomeness' THEN value ELSE null END ) awesomeness
FROM facts
WHERE id IN (1,2,3)
GROUP BY id
If you're using 11g, you could also use the PVOT
operator. 如果您使用的是11g,则还可以使用
PVOT
运算符。
If this is representative of your data model, though, that sort of entity-attribute data model is generally going to be rather inefficient. 但是,如果这代表您的数据模型,则这种类型的实体属性数据模型通常效率会很低。 You would generally be much better served with a table that had columns for
name
, height
, awesomeness
, etc. 通常,使用包含
name
, height
, awesomeness
等列的表会更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.