将具有相同ID但不同属性的记录合并到一个记录中

时间:2016-12-20 17:15:59

标签: sql sql-server tsql pivot

让我们说比如我有一张包含以下记录的表......

ID | Attribute
1      BLUE
1      GREEN
1      RED
2      YELLOW
2      GREEN
3      GREEN

我想将它压缩为包含所有属性的1条记录。

ID | Attribute1 | Attribute2 | Attribute3
1      BLUE         GREEN         RED
2      YELLOW       GREEN
3      GREEN

我正沿着PIVOT的道路前进,但不知道如何将属性明确地插入到不同的列中,因为它们共享相同的ID / Key。我正在使用SSMS。

3 个答案:

答案 0 :(得分:2)

如果您不需要动态,则条件聚合可能会有所帮助

Select ID
      ,max(case when RN=1 then Attribute else '' end)) as Attribute1 
      ,max(case when RN=2 then Attribute else '' end)) as Attribute2 
      ,max(case when RN=3 then Attribute else '' end)) as Attribute3
 From (
        Select *
              ,RN = Row_Number() over (Partition By ID Order By Attribute)
         From YourTable
      )
 Group By ID

答案 1 :(得分:2)

试试这个

table {
  border: 1px solid black;
}

th, td, tr {
  border: 1px solid black;
}

.one {
  border: 1px solid red;
}

如果您想使用未知数量的属性,那么

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div class="table-wrapper table-wrapper--no-scroll table-wrapper--row-header-border table-wrapper--no-cell-wrapping">
  <table>
    <thead>
      <tr>
        <td rowspan="2">&nbsp;</td>
          <th colspan="3" scope="colgroup" class="table-wrapper--no-top-border">Admissions Top Heading</th>
      </tr>
      <tr>
          <th scope-"col" class="table-wrapper--no-top-border">one</th>
          <th scope-"col" class="table-wrapper--no-top-border">two</th>
          <th scope-"col" class="table-wrapper--no-top-border">three</th>
          <th scope-"col" class="one">four</th>
          <th scope-"col" class="one">five</th>
          <th scope-"col" class="one">six</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th scope="row">March 2016</th>
        <td>###</td>
        <td>###</td>
        <td>###</td>
        <td>###</td>
        <td>###</td>
        <td>###</td>
      </tr>
      <tr>
        <th scope="row">April 2016</th>
        <td>###</td>
        <td>###</td>
        <td>###</td>
        <td>###</td>
        <td>###</td>
        <td>###</td>
      </tr>
      <tr>
        <th scope="row">May 2016</th>
        <td>###</td>
        <td>###</td>
        <td>###</td>
        <td>###</td>
        <td>###</td>
        <td>###</td>
      </tr>
    </tbody>
  </table>
</div>
</body>
</html>

答案 2 :(得分:0)

这应该有效并且使用起来非常简单

select * from(
        select 
             ID
            ,Attribute
            ,row_number() over(partition by ID order by Attribute) as AttributeNumber
        from [YourTable]
        group by ID
                ,Attribute
            )t1
PIVOT
(
MAX(Attribute)
FOR AttributeNumber in ([1],[2],[3])-- add more as needed
)piv