首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求一条SQL查询语句.该如何处理

2012-02-02 
求一条SQL查询语句.每天的公里统计表车队日期公里12006-7-75022006-7-76712006-7-88922006-7-845查询结果

求一条SQL查询语句.
每天的公里统计表
车队   日期               公里
1         2006-7-7       50
2         2006-7-7       67
1         2006-7-8       89
2         2006-7-8       45

查询结果为
车队     2006-7-7     2006-7-8
1           50                 89
2           67                 45
这么个查询语句如何实现?

[解决办法]
create table test(车队 int,日期 varchar(10),公里 int)
insert into test select 1, '2006-7-7 ',50
insert into test select 2, '2006-7-7 ',67
insert into test select 1, '2006-7-8 ',89
insert into test select 2, '2006-7-8 ',45

select 车队, max(case when 日期= '2006-7-7 ' then 公里 end) as '2006-7-7 ',
max(case when 日期= '2006-7-8 ' then 公里 end )as '2006-7-8 '
from test
group by 车队
[解决办法]
---- 给你一个动态的例子 ----
CREATE TABLE tb(car varchar(2),rq datetime,gl int)
INSERT tb SELECT '1 ', '2006-7-7 ', 50
UNION ALL SELECT '2 ', '2006-7-7 ', 67
UNION ALL SELECT '1 ', '2006-7-8 ', 89
UNION ALL SELECT '2 ', '2006-7-8 ', 45

select * from tb
DECLARE @s nvarchar(4000)
SET @s= 'SELECT car '
SELECT @s=@s
+ ', '+QUOTENAME(rq)
+N '=SUM(CASE rq WHEN '+QUOTENAME(rq,N ' ' ' ')
+N ' THEN gl END) '
FROM tb
GROUP BY rq
print (@s+N '
FROM tb
GROUP BY car ')

drop table tb
[解决办法]
create table test(车队 int,日期 smalldatetime,公里 int)
insert into test select 1, '2006-7-7 ',50
insert into test select 2, '2006-7-7 ',67
insert into test select 1, '2006-7-8 ',89
insert into test select 2, '2006-7-8 ',45

declare @sql varchar(8000)
set @sql= ' '

select
@sql=@sql+ ',[ '+t.日期+ ']=sum(case 日期 when ' ' '+t.日期+ ' ' ' then 公里 else 0 end) '
from
(select distinct convert(char(10),日期,120) as 日期 from test) t
order by
t.日期

set @sql= 'select 车队 '+@sql+ ' from test group by 车队 order by 车队 '

exec(@sql)

/*
车队 2006-7-7 2006-7-8
----------- ----------- -----------
1 50 89
2 67 45
*/


drop table test

热点排行
Bad Request.