如何按日期查询多列
答案 0 :(得分:2)
条件聚合是我的第一个方法
select V.DATE,
max(case when p.NAME = 'Meter1' then v.Value end) Meter1,
max(case when p.NAME = 'Meter2' then v.Value end) Meter2,
max(case when p.NAME = 'Meter3' then v.Value end) Meter2
from point p
join value v on v.ID = P.ID
GROUP BY V.DATE
编辑:您还应该使用PIVOT
Way
select * from
(
select p.Name, v.Date ,v.Value
from point p
join value v on v.ID = P.ID
)as a
PIVOT
(
MAX(Value) for Name in ([Meter1], [Meter2], [Meter3])
) pvt
答案 1 :(得分:1)
使用PIVOT
create table tblpoint(ID int,Name varchar(20))
create table tblValue(ID int,date1 date,value int)
insert into tblpoint values(1,'Meter1'),(2,'Meter2'),(3,'Meter3')
insert into tblValue values(1,'01-01-18',10),(2,'01-01-18',20),(3,'01-01-18',30),(1,'02-01-18',11),(2,'02-01-18',21),(3,'02-01-18',31)
select * from
(
select date1,value,Name from tblpoint a inner join tblValue b on a.ID=b.ID
)x
PIVOT
(
MAX(value)
for Name in ([Meter1],[Meter2],[Meter3])
)
as p;