我在SQL中有以下表格:
Name | Date | Property | Value
------------------------------------
Name1 | Date1 | PropertyA | Value11A
Name1 | Date1 | PropertyB | Value11B
Name1 | Date2 | PropertyA | Value12A
Name1 | Date2 | PropertyB | Value12B
Name2 | Date1 | PropertyA | Value21A
Name2 | Date1 | PropertyB | Value21B
Name2 | Date2 | PropertyA | Value22A
Name2 | Date2 | PropertyB | Value22B
------------------------------------
并希望得到以下输出:
Name | Date | PropertyAValue | PropertyBValue
-----------------------------------------------
Name1 | Date1 | Value11A | Value11B
Name1 | Date2 | Value12A | Value12B
Name2 | Date1 | Value21A | Value21B
Name2 | Date2 | Value22A | Value22B
我构造了一些适用于很多select / where语句的东西。但是,一旦有10个属性,查询就变得非常沉重。你能帮助提高效率吗?
编辑:我在Oracle上。我也看了一下pivot函数,但它只适用于聚合值,但我不会聚合任何东西,只重新格式化表并将一个值作为列。
答案 0 :(得分:1)
PIVOT
来实现您的目标:
SELECT Name, Date, [PropertyA] AS PropertyAValue , [PropertyB] AS PropertyBValue
FROM
(SELECT * FROM your_table) p
PIVOT
(
MAX(Value)
FOR Property IN ([PropertyA],[PropertyB])
) AS pvt
以下是SQL Fiddle
的代码这是上述查询的Oracle等效项:
SELECT *
FROM (SELECT Name, Date1, Property, Value
FROM your_table)
PIVOT (MAX(Value) FOR (Property) IN ('PropertyA' AS PropertyA, 'PropertyB' AS PropertyB))
ORDER BY Name, Date1;
以下是SQL Fiddle
的代码