SQLSERVER行转列和列转行

1: 行转列

子查询,获取一定数据集结果

```

SELECT objid,action,count(1) AS [count] FROM T_MyAttention WHERE objid IN

(SELECT TOP 10 objid FROM T_MyAttention tma GROUP BY objid ORDER BY count(1) DESC)

GROUP BY objid,action

```

下面用 行转列语法获取 最终结果

```

select *

from

(

SELECT objid,action,count(1) AS [count] FROM T_MyAttention WHERE objid IN

(SELECT TOP 10 objid FROM T_MyAttention tma GROUP BY objid ORDER BY count(1) DESC)

GROUP BY objid,action

) t

pivot ( sum(count) for t.action in ([1],[2],[3],[4])) as ourpivot

```

ps:挺好挺使用的功能,微软为啥子不内置在SQLserver里呢,ms,唉!

微软官方的图:


你可能感兴趣的:(SQLSERVER行转列和列转行)