0

我有一个表 Task 有一个 createdDate 列。我需要获取在特定月份创建的所有任务,并且每天的记录不应超过 4 条。如果在特定日期有超过 4 条记录,那么我们只能获取最先创建的前 4 条记录。还有另一列 CreatedTime。

Task
(
  id
  ,CreatedDate
  ,CreatedTime

)

结果应该是

id      CreatedDate

1       1/1/2013  
2       1/1/2013  
3       1/1/2013  
4       1/1/2013  
5       1/2/2013  
6       1/2/2013  
7       1/2/2013  
8       1/2/2013  
4

3 回答 3

0

ROW_NUMBER()在子查询或公用表表达式 (CTE) 中使用。子查询版本:

SELECT
    * --TODO: Columns
FROM
    (SELECT
        *,ROW_NUMBER() OVER (PARTITION BY CreatedDate ORDER BY CreatedTime) as rn
     FROM
        Task
    ) t
WHERE
    rn between 1 and 4

如果您的数据中可能存在关联(CreatedTime同一天的两行相同)并且您需要明确考虑这些关联,则可以根据需要ROW_NUMBER使用RANKor交换DENSE_RANK

于 2013-02-11T08:03:55.667 回答
0
; WITH A AS (
SELECT ID, CreatedDate
, convert(VARCHAR(7), CreatedDate, 121) AS YearMonth --will return something like 2012-01 
FROM Task
), 
B AS (
SELECT ID, CreatedDate
, ROW_NUMBER() OVER (PARTITION BY YearMonth ORDER BY CreatedDate, ID) AS RowNum
FROM A)
SELECT ID, CreatedDate
FROM B
WHERE RowNum<=4
ORDER BY ID

这适用于 SQL 2005 和更高版本。

  1. 首先在 CTE A 中找到分区列(年月),
  2. 然后在 B 中为每条记录分配一个 RowNum(这可以根据您的订购条件进行更改)
  3. 然后你得到最终的结果。
于 2013-02-11T08:11:29.220 回答
0

谢谢你的回复。我做了一些改变并在这里得到了解决方案。

; WITH A 
AS 
(
SELECT ID, CreatedDate , DAY(CreatedDate) AS Day 
FROM Task
WHERE CreatedDate BETWEEN '01/01/2013 00:00:00' AND '01/31/2013 23:59:59' 
)
,
B AS 
(
    SELECT 
     ROW_NUMBER() OVER (PARTITION BY Day ORDER BY CreatedDate, ID) AS RowNum 
    ,*
    FROM A
)


select 
 DAY(CreatedDate) as Day1
, MONTH(CreatedDate) as Month
, YEAR(dueDate) as Year
, * 
from B 
WHERE RowNum <= 4
order by Year,Month,Day1, CreatedDate
于 2013-02-11T10:07:46.343 回答