查询以获取列名和值

时间:2018-10-18 12:02:24

标签: sql sql-server select

我有一个看起来像这样的表:

CO['new'] = CO.apply(lambda row: sum_neighbors(data, row.p3), axis=1)

我想返回一个像这样的表:

emplid      year        JAN     FEB     MAR     APR     MAY
------      ----        ---     ---     ---     ---     ---
1234        2018         x       x       x     Retire
5678        2018         x   Terminated
9876        2018         x       x       x       x    Transfer
5432        2018         x       x       x       x       x

基本上,我想找到一名雇员退休,辞职,被解雇等的年月,以及原因。反正有做到这一点吗?我正在使用ms sql服务器。如果您需要其他任何信息,请告诉我。我不知道该怎么做。超越了我的专业水平。谢谢

4 个答案:

答案 0 :(得分:3)

有一个非常方便的使用APPLY的地方:

select t.empid, t.year, v.mon, v.reason
from t cross apply
     (values ('JAN', jan), ('FEB', feb), ('MAR', mar), ('APR', apr), ('MAY', may)
     ) v(mon, reason)
where reason <> 'x';

答案 1 :(得分:2)

将以下查询范围扩展到从6月到DEC的剩余月份

SELECT emplid,year,
CASE WHEN JAN <> 'x' THEN 'JAN' 
     WHEN FEB <> 'x' THEN 'FEB'
     WHEN MAR <> 'x' THEN 'MAR'
     WHEN APR <> 'x' THEN 'APR'
     WHEN MAY <> 'x' THEN 'MAY'

--Rest of months
END [month],
REPLACE(JAN+FEB+MAR+APR+MAY,'x','') Reason
FROM tableName

答案 2 :(得分:0)

您的表只是未规范化,但是... 您可以使用:

select emplid, year, 
case 
when not (JAN = 'x')
  then 'JAN'
when not (FEB = 'x')
  then 'FEB'
as month

,原因相同。

答案 3 :(得分:0)

尝试this

select t1.emplid,t1.year,
(
  CASE 
    WHEN t1.JAN <> 'x' AND t1.JAN <> '' THEN 'JAN'
    WHEN t1.FEB <> 'x' AND  t1.FEB <> '' THEN 'FEB'
    WHEN t1.MAR <> 'x' AND  t1.MAR <> '' THEN 'MAR'
    WHEN t1.APR <> 'x' AND  t1.APR <> '' THEN 'APR'
    WHEN t1.MAY <> 'x' AND  t1.MAY <> '' THEN 'MAY'
  end
)  as month,
(
  CASE 
    WHEN t1.JAN <> 'x' AND t1.JAN <> '' THEN t1.JAN
    WHEN t1.FEB <> 'x' AND  t1.FEB <> '' THEN t1.FEB
    WHEN t1.MAR <> 'x' AND  t1.MAR <> '' THEN t1.MAR
    WHEN t1.APR <> 'x' AND  t1.APR <> '' THEN t1.APR
    WHEN t1.MAY <> 'x' AND  t1.MAY <> '' THEN t1.MAY 
  end
)  as Reason
 from table1 t1
 where Reason  is not null