将列更改为MySQL DB中的行

时间:2013-09-23 11:41:31

标签: mysql sql

我在MySQL的临时表中有这些列

DetectionDate,CountSyslogs,CountTraps,CountNetworkOriginatedEvents,CountNetworkServicesEvents
2013-09-21       66            55           88                            150
2013-09-23       99            100         150                            200

我需要显示这样的数据

DetectionDate,orderNum,  Type                        ,count
2013-09-21       1      Syslogs                       66
2013-09-23       1      Syslogs                       99
2013-09-21       2      Traps                         55
2013-09-23       2      Traps                         100
2013-09-21       3      NetworkOriginatedEvent        88
2013-09-23       3      NetworkOriginatedEvent        150
2013-09-21       4      NetworkServicesEvents         150
2013-09-23       4      NetworkServicesEvents         200

1 个答案:

答案 0 :(得分:2)

SELECT DetectionDate,
       1 AS ordernum,
       'syslogs' AS TYPE,
       countsyslogs AS COUNT
FROM TABLE
UNION ALL
SELECT DetectionDate,
       2 AS ordernum,
       'traps' AS TYPE,
       counttraps AS COUNT
FROM TABLE
UNION ALL
SELECT DetectionDate,
       3 AS ordernum,
       'NetworkOriginatedEvent' AS TYPE,
       CountNetworkOriginatedEvents AS COUNT
FROM TABLE
UNION ALL
SELECT DetectionDate,
       4 AS ordernum,
       'NetworkServicesEvents' AS TYPE,
       CountNetworkServicesEventsas COUNT
FROM TABLE

没有多个选择: 试试这个:

SELECT DetectionDate,
       b.rank,
      case rank
 when 1 then 'sys'
 when 2 then ....
end as type,
      case rank
 when 1 then countsyslogs
 when 2 then ....
end as count

from table, (select 1 as rank union select 2 union select 3 union select 4)b