如何按日期查询

时间:2018-01-29 04:55:16

标签: sql sql-server

如何按日期查询多列

Output

2 个答案:

答案 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;

Demo