在SQL

时间:2015-10-15 19:01:14

标签: sql-server sql-server-2008 join pivot

我已经设法将现有的行转换为列,但是不是生成1行,而是使用相同的容器生成2行。这是我的数据集。

SELECT distinct c.container, c.attribute, c.value, c.property from cars c
WHERE c.container = 'VOLVO'

---------------------------------------------------
| CONTAINER |  ATTRIBUTE |   VALUE   | PROPERTY |
|  VOLVO    |    TIRE    |   DUNLOP  |     A    |
|  VOLVO    |    SEATS   |     4     |     A    |
|  VOLVO    |    PRICE   |   25,000  |     B    |
|  VOLVO    |    COLOR   |    BLUE   |     A    |
|  VOLVO    |    MODEL   |    XC90   |     A    |


SELECT * FROM cars
PIVOT( max(value) for attribute IN ([TIRE],[SEATS],[PRICE],[COLOR],[MODEL])) P
WHERE container = 'VOLVO'

---------------------------------------------------------------------------
| CONTAINER |  PROPERTY |    TIRE    | SEATS |   PRICE  |  COLOR  |  MODEL
---------------------------------------------------------------------------
| VOLVO     |     A     |   DUNLOP   |   4   |   NULL   |  BLUE   |  XC90
| VOLVO     |     B     |   NULL     |  NULL |  25,000  |  NULL   |  NULL

我如何合并这两行并产生这个结果?

---------------------------------------------------------------------------
| CONTAINER |  PROPERTY |    TIRE    | SEATS |   PRICE  |  COLOR  |  MODEL
---------------------------------------------------------------------------
| VOLVO     |     A     |   DUNLOP   |   4   |  25,000  |  BLUE   |  XC90

谢谢!

1 个答案:

答案 0 :(得分:1)

你需要遗漏财产:

SELECT * FROM (
  select CONTAINER, VALUE, ATTRIBUTE from cars
) S
PIVOT( max(value) for attribute IN ([TIRE],[SEATS],[PRICE],[COLOR],[MODEL])) P
WHERE container = 'VOLVO'

结果:

CONTAINER   TIRE    SEATS   PRICE   COLOR   MODEL
VOLVO       DUNLOP  4       25,000  BLUE    XC90

SQL Fiddle