日期:2014-05-17  浏览次数:20401 次

关于SQL写法问题


ID   SL      TIME
1    1    2013-4-1
2    2    2013-4-2
1    1    2013-4-4
2    1    2013-4-4



语句要求


查询2013-4-1至2013-4-5 的字段ID 为1和2  的字段SL之和  不能重复

------解决方案--------------------
select sum(sl) from (
select distinct ID,sl from 表 where time between '2013-4-1' and '2013-4-5'
)a
------解决方案--------------------
select SUM(s) from (
select max(sl) s from 表 where [time] Between '2013-04-01' And '2013-04-05'
group by id) a
------解决方案--------------------
create table tab3
(
 ID int,SL int,time date
)
insert into tab3
select 1,1,'2013-04-01' union all
select 2,2,'2013-04-02' union all
select 1,1,'2013-04-03' union all
select 2,1,'2013-04-04' 

select ID,sum(SL) SL from (
select ID,SL 
from tab3
) b group by ID
ID          SL
----------- -----------
1           2
2           3

(2 行受影响)


------解决方案--------------------
select ID,sum(SL) SL from (
select ID,SL 
from tab3 where [time] Between '2013-04-01' And '2013-04-05'
) b    group by ID

------解决方案--------------------
select max(id) id,sum(sl) sl from 表 where [time] Between '2013-04-01' And '2013-04-05'
 group by id
------解决方案--------------------
select  id,sum(sl) sl from dbo.test1 where [time] Between '2013-04-01' And '2013-04-05'
 group by id
------解决方案--------------------
select distinct ID,sum(SL) SL 
from 
(
select ID,SL 
from tab3 
where [time] Between '2013-04-01' And '2013-04-05'
) b 
group by ID