您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在有条件的情况下透视表中的行?

如何在有条件的情况下透视表中的行?

有几种不同的方法可以得到结果。

您可以使用条件逻辑将具有CASE表达式的聚合函数应用于创建新列:

select datetime,
  max(case when name = 'machine-2' then cpu_usage end) machine2,
  max(case when name = 'machine-3' then cpu_usage end) machine3,
  max(case when name = 'machine-4' then cpu_usage end) machine4,
  max(case when name = 'machine-5' then cpu_usage end) machine5
from yourtable
group by datetime;

参见带有演示的SQL Fiddle

或者,您可以应用PIVOT函数,该函数会将您的name值转换为列:

select datetime,
  [machine-2], [machine-3], 
  [machine-4], [machine-5]
from
(
  select datetime, name, cpu_usage
  from yourtable
) d
pivot
(
  max(cpu_usage)
  for name in ([machine-2], [machine-3], [machine-4], [machine-5])
) piv;

请参阅带有演示的SQL Fiddle

如果name列的值数量有限,则以上两个版本将为您工作,但是如果没有,那么您将需要使用动态sql

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(name) 
                    from yourtable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT datetime,' + @cols + ' 
            from 
            (
              select datetime, name, cpu_usage
              from yourtable
            ) x
            pivot 
            (
                max(cpu_usage)
                for name in (' + @cols + ')
            ) p '

execute sp_executesql @query;

请参阅带有演示的SQL Fiddle。所有版本都会产生结果:

|                        DATETIME | MACHINE-2 | MACHINE-3 | MACHINE-4 | MACHINE-5 |
|---------------------------------|-----------|-----------|-----------|-----------|
| November, 18 2013 17:00:22+0000 |   50.6693 |   19.8329 |   24.2103 |    (null) |
| November, 18 2013 17:01:22+0000 |   97.2774 |   66.2991 |    (null) |   26.6446 |
| November, 18 2013 17:02:22+0000 |   39.5881 |        99 |   85.0968 |    (null) |
其他 2022/1/1 18:49:14 有578人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶