--假设数据表如下
create table price(编码 varchar(50), 名称 varchar(50), 单价 decimal(20,2), 时间 datetime)
insert into price select '1001','法式椰风月饼','12.50','2012-09-13 07:00:00'
insert into price select '1001','法式椰风月饼','13.50','2012-09-13 12:00:00'
insert into price select '1001','法式椰风月饼','14.50','2012-09-13 14:00:00'
insert into price select '1001','法式椰风月饼','13.50','2012-09-13 18:00:00'
insert into price select '1001','法式椰风月饼','12.50','2012-09-13 21:00:00'
insert into price select '1002','法式蓝莓月饼','12.80','2012-09-13 07:00:00'
insert into price select '1002','法式蓝莓月饼','13.80','2012-09-13 12:00:00'
insert into price select '1002','法式蓝莓月饼','14.80','2012-09-13 14:00:00'
insert into price select '1002','法式蓝莓月饼','13.80','2012-09-13 18:00:00'
insert into price select '1002','法式蓝莓月饼','12.80','2012-09-13 21:00:00'
--按以下sql,可以查询每天3个不同时间段的最高单价
select 编码,名称,
max(case 时间段 when 1 then 单价 else 0 end) 单价1,
max(case 时间段 when 2 then 单价 else 0 end) 单价2,
max(case 时间段 when 3 then 单价 else 0 end) 单价3
from(
select 编码,名称,单价,
(case
when datepart(hour,时间)>=0 and datepart(hour,时间)<8 then 1
when datepart(hour,时间)>=8 and datepart(hour,时间)<18 then 2
else 3
end
) 时间段
from price) a group by 编码,名称
查询结果为:
'编码' '名称' '单价1' '单价2' '单价3'
'1002' '法式蓝莓月饼' 12.80 14.80 13.80
'1001' '法式椰风月饼' 12.50 14.50 13.50
按照你的意思可以用max()over(order by xxx rows ....) 取一段时间内的最大值
Select,名称,
Max(Case When lasteditdt Between '20120101' And '20120201' Then 单价 Else 0 End) 单价1
Max(Case When lasteditdt Between 时间3 And 时间4 Then 单价 Else 0 End) 单价2
Max(Case When lasteditdt Between 时间5 And 时间6 Then 单价 Else 0 End) 单价3
From Table Group By 名称
select top 1 编码,名称,单价,时间 from Table where time between '2012-1-1 00:00:01' and '2012-01-31 23:59:59'
单价1,单价2,单价3代表什麼?