求一条SQL查询语句.

ffsquare 2007-06-13 02:24:04
每天的公里统计表
车队 日期 公里
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
这么个查询语句如何实现?
...全文
155 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
ffsquare 2007-06-13
  • 打赏
  • 举报
回复
好了,非常感谢libin_ftsafe(子陌红尘:TS for Banking Card) 用你的方法已经实现了.
回复也很快速,呵呵.
也感谢leo_lesley(leo) ,虽然你给的方法的出来的格式和我要的不同,但也谢谢你.
子陌红尘 2007-06-13
  • 打赏
  • 举报
回复
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
ffsquare 2007-06-13
  • 打赏
  • 举报
回复
为什么我用libin_ftsafe(子陌红尘:TS for Banking Card)方法在执行的时候说
从字符串转换为 smalldatetime 数据类型时发生语法错误。
怎么解决? 表中日期字段是smalldatetime类型的.
leo_lesley 2007-06-13
  • 打赏
  • 举报
回复
---- 给你一个动态的例子 ----
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
ojuju10 2007-06-13
  • 打赏
  • 举报
回复
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 车队
子陌红尘 2007-06-13
  • 打赏
  • 举报
回复
以上是动态SQL实现的方式,如果日期固定,则可以使用以下SQL:

select
车队,
[2006-7-7]=sum(case 日期 when '2006-7-7' then 公里 else 0 end),
[2006-7-8]=sum(case 日期 when '2006-7-8' then 公里 else 0 end)
from
test
group by
车队
order by
车队
子陌红尘 2007-06-13
  • 打赏
  • 举报
回复
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



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

select @sql=@sql+',['+日期+']=sum(case 日期 when '''+日期+''' then 公里 else 0 end)' from test group by 日期

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

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧