基础数据:
主表
id 金额 日期
1 200 2009-01-14
2 300 2009-01-14
3 300 2009-01-14从表
id 主表id 型号
1 1 2
2 1 3
3 2 2
4 3 2 形成以下查询数据:
日期 型号2 型号3 总金额
2009-01-14 3 1 800求sql写法
主表
id 金额 日期
1 200 2009-01-14
2 300 2009-01-14
3 300 2009-01-14从表
id 主表id 型号
1 1 2
2 1 3
3 2 2
4 3 2 形成以下查询数据:
日期 型号2 型号3 总金额
2009-01-14 3 1 800求sql写法
解决方案 »
- 如何按编号获取最小批次数据
- 我是初学者 希望大家多多指教 谢谢了
- 如何知道sql server 绑定在双网卡的哪块网卡
- 为什么在Dreamweaver里看不到Sql下我自己建的表呢???大家帮忙
- sqlserver update 进行一半 客户端死机 sqlserver服务怎么办
- 求救!!!想把图片资料存入数据库
- 我打算用sql sever2000建立一个数据源,再用ado连接。但是,我怎么就是连接不到呢?是不是,要先建个数据库?怎么建呢?建了以后怎么办呢
- 请教!
- sqlserver Agent 执行备份计划时出错
- 菜鸟请教关于数据库驱动程序的概念问题
- SQL2000 中EXISTS没有执行检查??????很奇怪========
- 求一sql 写法
if object_id('[s]') is not null drop table [s]
create table [s] (id int,pid int,bm varchar(8))
insert into [s]
select 7,2,'单位1' union all
select 8,2,'单位22' union all
select 9,2,'单位3333' union all
select 10,3,'单位1' union all
select 11,3,'单位22' union all
select 12,3,'单位22'declare @sql varchar(1000)
set @sql='select pid'
select @sql=@sql+',[bm'+ltrim(px)+']=max(case px when '''+ltrim(px)+''' then bm else '''' end)'
from (select distinct px=(select count(1) from s where pid=a.pid and id<=a.id) from [s] a)a
set @sql=@sql+' from (select px=(select count(1) from s where pid=a.pid and id<=a.id),* from [s] a)a group by pid'
exec(@sql)
sum(case when b.型号=3 then 1 else 0 end) 型号3,
sum(a.金额) 总金额
from 主表 a join 从表 b on a.id=b.主表id group by a.日期
insert 主表 values(1, 200, '2009-01-14')
insert 主表 values(2 , 300 ,'2009-01-14')
insert 主表 values(3 ,300 ,'2009-01-14')create table 从表(id int,主表id int,型号 int)
insert 从表 values(1, 1 ,2)
insert 从表 values(2, 1, 3)
insert 从表 values(3 , 2 , 2)
insert 从表 values(4 ,3 , 2 )select a.日期,sum(case when b.型号=2 then 1 else 0 end) 型号2,
sum(case when b.型号=3 then 1 else 0 end) 型号3,
(select sum(金额) from 主表 where 日期=a.日期) 总金额
from 主表 a join 从表 b on a.id=b.主表id group by a.日期
/*
日期 型号2 型号3 总金额
----------------------- ----------- ----------- -----------
2009-01-14 00:00:00.000 3 1 800
*/