我想转换此表/查询
+--------+-----------------+-----------------+
| tag_id | attribute_name | attribute_value |
+--------+-----------------+-----------------+
| 1 | tag_name | P1001 |
| 1 | tag_address | N7:0 |
| 1 | tag_description | Pump 1 Status |
| 2 | tag_name | P1002 |
| 2 | tag_address | N7:1 |
| 2 | tag_description | Pump 2 Status |
| 3 | tag_name | P1003 |
| 3 | tag_address | N7:2 |
| 3 | tag_description | Pump 3 Status |
+--------+-----------------+-----------------+
到这个
+----------+-------------+-----------------+
| tag_name | tag_address | tag_description |
+----------+-------------+-----------------+
| P1001 | N7:0 | Pump 1 Status |
| P1002 | N7:1 | Pump 2 Status |
| P1003 | N7:2 | Pump 3 Status |
+----------+-------------+-----------------+
我知道交叉表查询存在,但它迫使我为Value选择一个聚合函数。如果我选择First
或Max
它可行,但它不是最有效的方式。有更好的方法吗?
答案 0 :(得分:0)
select tag_name, tag_address, tag_description from
(
(
select tag_id, attribute_value as tag_name
from inputtable
where attribute_name='tag_name'
) as one
left join
(
select tag_id, attribute_value as tag_address
from inputtable
where attribute_name='tag_address'
) as two
on one.tag_id=two.tag_id
)
left join
(
select tag_id, attribute_value as tag_description
from inputtable
where attribute_name='tag_description'
) as three
on one.tag_id=three.tag_id
答案 1 :(得分:0)
正如您在问题中所建议的那样,
TRANSFORM MAX(attribute_value) AS thing
SELECT tag_id
FROM your_table
GROUP BY tag_id
PIVOT attribute_name IN ('tag_name','tag_address','tag_description')
会奏效。另一种选择是
SELECT tn.tag_name, ta.tag_address, td.tag_description
FROM
(
(
SELECT
tag_id,
attribute_value AS tag_name
FROM your_table
WHERE attribute_name = 'tag_name'
) AS tn
INNER JOIN
(
SELECT
tag_id,
attribute_value AS tag_address
FROM your_table
WHERE attribute_name = 'tag_address'
) AS ta
ON ta.tag_id = tn.tag_id
)
INNER JOIN
(
SELECT
tag_id,
attribute_value AS tag_description
FROM your_table
WHERE attribute_name = 'tag_description'
) AS td
ON td.tag_id = tn.tag_id
但我可能只是选择第一个。