读书人

关于SQL写法有关问题

发布时间: 2013-04-21 21:18:07 作者: rapoo

关于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

读书人网 >SQL Server

热点推荐