select devicename, name, value, timestamp from table1
给了我以下内容,
DEVICENAME NAME VALUE TIMESTAMP
123 CURRENT 130 2012-10-16 13:00:00.000
123 AVG 140 2012-10-16 13:00:00.000
123 MIN 100 2012-10-16 13:00:00.000
123 MAX 160 2012-10-16 13:00:00.000
我如何在sql查询中得到它们,
123, 130, 140, 100, 160 2012-10-16 13:00:00.000
答案 0 :(得分:3)
如果您希望在单独的列中使用PIVOT
,可以使用select devicename, [Current], [Avg], [Min], [Max], timestamp
from
(
select devicename, name, value, timestamp
from table1
) x
pivot
(
max(value)
for name in ([Current], [Avg], [Min], [Max])
) p
:
select devicename,
STUFF((SELECT distinct ', ' + cast(value as varchar(10))
from table1 t2
where t1.DEVICENAME = t2.DEVICENAME
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
,1,1,'') name,
timestamp
from table1 t1
group by devicename, timestamp
如果您想要同一列中的所有值,则可以使用以下内容:
{{1}}
答案 1 :(得分:2)
select
devicename,
MAX(CASE WHEN Name = 'CURRENT' THEN value ELSE NULL END),
MAX(CASE WHEN Name = 'AVG' THEN value ELSE NULL END),
MAX(CASE WHEN Name = 'MIN' THEN value ELSE NULL END),
MAX(CASE WHEN Name = 'MAX' THEN value ELSE NULL END),
timestamp
from table1
GROUP BY devicename, timestamp
答案 2 :(得分:0)
您可以将它们连接成一列
select a + ' '+ b as Column1 from yourtable
或将它们作为输出变量返回
答案 3 :(得分:0)
SELECT x.devicename, *
FROM
(SELECT devicename, value as 'current', timestamp
FROM table1 WHERE name = 'current') x
INNER JOIN
(SELECT devicename, value as [avg] FROM table1 WHERE name = 'avg') y
ON x.devicename = y.devicename
INNER JOIN (SELECT devicename, value as [min] FROM table1 WHERE name = 'min') z
ON x.devicename = z.devicename
INNER JOIN (SELECT devicename, value as [max] FROM table1 WHERE name = 'max') q
ON x.devicename = q.devicename
答案 4 :(得分:-1)
create table table1 (devicename varchar(10)
,name varchar(100)
,value varchar(10)
,TimeSTamp datetime)
INSERT INTO table1
SELECT '123','CURRENT','130','2012-10-16 13:00:00.000'
UNION
SELECT '123','AVG','140','2012-10-16 13:00:00.000'
UNION
SELECT '123','MIN','100','2012-10-16 13:00:00.000'
UNION
SELECT '123','MAX','160','2012-10-16 13:00:00.000'
select devicename, name, value, timestamp from table1
SELECT DISTINCT t1.devicename
, value_list
, t1.timestamp
FROM table1 t1
INNER JOIN (SELECT t2.devicename
, t2.timestamp
, value_list = SUBSTRING((SELECT t3.value
+ ', '
FROM table1 t3
WHERE t3.devicename = t2.devicename
AND t3.timestamp = t2.timestamp
ORDER BY t3.value
FOR XML PATH('')),1,LEN((SELECT t3.value
+ ', '
FROM table1 t3
WHERE t3.devicename = t2.devicename
AND t3.timestamp = t2.timestamp
ORDER BY t3.value
FOR XML PATH(''))) -1)
FROM table1 t2
GROUP BY t2.devicename
, t2.timestamp) t4 on t4.devicename = t1.devicename
AND t4.timestamp = t1.timestamp
drop table1