如何从多行中选择值到单行的列中?

时间:2014-03-18 05:41:35

标签: sql sql-server

我有一个表EventInfo,其中包含与单个事件相关的多行信息:

EventFK  ParameterType  Value
1        123            computer1
1        124            userX
1        124            20140318
2        123            computer2
2        124            userY
2        124            20140317
3        123            computer3
3        124            userX
3        124            20140318

我只对事件2和3的数据感兴趣。我最终想要的是:

EventFK  PCName     UserName  Date
2        computer2  userY     20140317
3        computer3  userX     20140318

在使用STUFF将EventInfo中的多行连接成一个以逗号分隔的字符串之前,我已经完成了这个。

我希望最终得到正确的列,以便我可以轻松地将其映射到C#Windows窗体应用程序中的DataGridView。

我可以对临时表执行某些操作 - 根据三个SELECT语句的值插入一个新行吗?

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT EventFK,MAX(PCName) as PCName, MAX(UserName) as UserName,MAX(Date) as Date 
FROM (
      SELECT EventFK,
         CASE ParameterType WHEN 123 THEN Value ELSE '' END as PCName ,
         CASE WHEN ParameterType= 124 AND value LIKE '%[^0-9]%' THEN Value ELSE '' END as UserName ,
         CASE WHEN ParameterType= 124 AND value NOT LIKE '%[^0-9]%' THEN Value ELSE '' END as Date 
      FROM TableName
     ) T
WHERE EventFK IN (2,3)
GROUP BY EventFK

结果是:

EVENTFK     PCNAME      USERNAME    DATE
2           computer2   userY       20140317
3           computer3   userX       20140318

请参阅SQL Fiddle

中的结果

答案 1 :(得分:1)

您可以使用ROW_NUMBER()PARTITION为要转置为列的值指定一个键,然后使用该键进行转置,如下所示:

;with x as
(select EVENTFK, value val, ROW_NUMBER() over (partition by eventfk order by parametertype, value) rn
from YourTable where EVENTFK <> 1),
r1 as (select EVENTFK rid1, val PCNAME from x where x.rn =1),
r2 as (select EVENTFK rid2, val DATE from x where x.rn =2),
r3 as (select EVENTFK rid3, val USERNAME from x where x.rn =3)
select distinct EVENTFK, PCNAME, USERNAME, DATE
from x inner join r1 on x.EVENTFK = r1.rid1
inner join r2 on x.EVENTFK = r2.rid2
inner join r3 on x.EVENTFK = r3.rid3