如何将行值转换为列

时间:2017-05-28 09:18:47

标签: sql pivot-table

我有下表。我们只是叫它电话

--------------------------
| userid | type | number |
--------------------------
| 1      | home | 123456 |
--------------------------
| 1      |office| 654321 |
--------------------------

所以我希望它是这样的:

--------------------------
| userid | home | office |
--------------------------
| 1      |123456| 654321 |
--------------------------

我正在尝试数据透视表,但问题是我没有任何字段要聚合。有什么建议吗?

PS 我正在使用Azure SQL Server

2 个答案:

答案 0 :(得分:1)

一种方法是:

p {
  font-family: Calibri;
  font-size: 14px;
  font-weight: bolder;
  text-align: left;
}

p.fade {
  color: #CCCCCC;
  font-size: 14px;
}

em {
  font-style: italic;
  font-size: 16px;
  font-weight: lighter;
}

em.pass {
  font-style: italic;
  font-size: 16px;
  color: green;
}

em.fail {
  font-style: italic;
  font-size: 16px;
  color: red;
}

a {
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}

hr {
  align: left;
  margin-left: 0px;
  width: 500px;
  height: 1px;
}

table {
  border-collapse: collapse;
}

tr {
  padding: 4px;
  text-align: center;
  border-right: 2px solid #FFFFFF;
}

tr:nth-child(even) {
  background-color: #f2f2f2
}

th {
  background-color: #cceeff;
  color: black;
  padding: 4px;
  border-right: 2px solid #FFFFFF;
}

如果<table> <tr> <th>AAA</th> <th>BBB</th> </tr> <tr> <td>CCC</td> <td>DDD</td> </tr> <tr style="color:red"> <!-- Here --> <td>EEE</td> <td>FFF</td> </tr> <tr> <td>GGG</td> <td>HHH</td> </tr> </table>列中还有其他值,并且您需要将它们显示为列,那么您还应添加另一个子查询和with your_table( userid , type , number) as ( select 1 ,'home','123456' union all select 1 ,'office','654321' union all select 2 ,'home','4444' union all select 3 ,'office','77777' ) -- below is actual query: select coalesce(t1.userid, t2.userid) as userid, t1.home, t2.office from (select userid, number as home from your_table where type = 'home') t1 full join (select userid, number as office from your_table where type = 'office' ) t2 on t1.userid = t2.userid

答案 1 :(得分:0)

如果您没有重复值:

select 
    user_id,
    min(case when type='home' then type else null end) home,
    min(case when type='office' then type else null end) office
from
    phone
group by
    userid;