34,588
社区成员
发帖
与我相关
我的任务
分享
DECLARE @TB TABLE(ID INT, time SMALLDATETIME, core INT)
INSERT @TB
SELECT 9587, '2008/01/01', 10 UNION ALL
SELECT 9586, '2008/02/01', 20 UNION ALL
SELECT 9587, '2008/05/04', 21 UNION ALL
SELECT 9587, '2008/07/01', 15 UNION ALL
SELECT 9587, '2008/04/01', 30
SELECT *,ID2=IDENTITY(INT,1,1) INTO # FROM @TB ORDER BY ID,time
SELECT ID,SUM(CORE) AS CORE
FROM (SELECT *,SEQ=ID2-(SELECT COUNT(*) FROM # WHERE ID<A.ID) FROM # AS A) T
WHERE SEQ<=3
GROUP BY ID
ORDER BY ID
DROP TABLE #
/*
ID CORE
----------- -----------
9586 20
9587 61
*/
select top 3 sum(core) from 表 order by time
DECLARE @TB TABLE(ID INT, time SMALLDATETIME, core INT)
INSERT @TB
SELECT 9587, '2008/01/01', 10 UNION ALL
SELECT 9586, '2008/02/01', 20 UNION ALL
SELECT 9587, '2008/05/04', 21 UNION ALL
SELECT 9587, '2008/07/01', 15 UNION ALL
SELECT 9587, '2008/04/01', 30
SELECT *,ID2=IDENTITY(INT,1,1) INTO # FROM @TB ORDER BY ID,time
SELECT SUM(CORE) AS CORE
FROM #
WHERE ID2<=3
DROP TABLE #
/*
CORE
-----------
60
*/
---------------------------------
-- Author: liangCK 小梁
-- Date : 2008-12-08 11:40:51
---------------------------------
--> 生成测试数据: @T
DECLARE @T TABLE (ID INT,time DATETIME,core INT)
INSERT INTO @T
SELECT 9587,'2008/01/01',10 UNION ALL
SELECT 9586,'2008/02/01',20 UNION ALL
SELECT 9587,'2008/05/04',21 UNION ALL
SELECT 9587,'2008/07/01',15 UNION ALL
SELECT 9587,'2008/04/01',30
--SQL查询如下:
SELECT DISTINCT
B.ID,
MAX(B.time) AS time,
SUM(B.core) AS core
FROM (
SELECT DISTINCT ID FROM @T
)AS A
CROSS APPLY(
SELECT TOP(3)
*
FROM @T
WHERE ID=A.ID
ORDER BY time
) AS B
GROUP BY B.ID
/*
ID time core
----------- ----------------------- -----------
9586 2008-02-01 00:00:00.000 20
9587 2008-05-04 00:00:00.000 61
(2 行受影响)
*/
select sum(core) from (select top 3 * from tb order by time)T
--借小梁的测试数据:
DECLARE @T TABLE (ID INT,time DATETIME,core INT)
INSERT INTO @T
SELECT 9587,'2008/01/01',10 UNION ALL
SELECT 9586,'2008/02/01',20 UNION ALL
SELECT 9587,'2008/05/04',21 UNION ALL
SELECT 9587,'2008/07/01',15 UNION ALL
SELECT 9587,'2008/04/01',30
--SQL查询如下:
select id,sum(core) as sum_core
from @t a
where time in (select top 3 time from @t where id = a.id order by time)
group by id
--结果集
/*
id sum_core
----------- -----------
9586 20
9587 61
(2 行受影响)
*/
select distinct [ID],
(select sum(core) from
(select top 3 core from @tb where [ID]=t.[ID] order by [time]) a )
from @TB t