2

我需要获取 Decemember 2012 到 2014 年 11 月之间的数据。

每个月我只需要 1500 行。

例如:

SELECT * FROM data WHERE YEAR(submit_date) = 2012 AND MONTH(submit_date) = 12 limit 1500;
SELECT * FROM data WHERE YEAR(submit_date) = 2013 AND MONTH(submit_date) = 1 limit 1500;
SELECT * FROM data WHERE YEAR(submit_date) = 2013 AND MONTH(submit_date) = 2 limit 1500;
SELECT * FROM data WHERE YEAR(submit_date) = 2013 AND MONTH(submit_date) = 3 limit 1500;
and until Nov 2014

有没有办法编写更小的 SQL 查询?

4

3 回答 3

2

这里有一些选项列表:http ://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/

恕我直言,最好的方法之一是使用行计数器:

set @num := 0, @type := '';

select id, name, submit_date,
  @num := if(@type = CONCAT(YEAR(submit_date), MONTH(submit_date)), @num + 1, 1) as row_number,
  @type := CONCAT(YEAR(submit_date), MONTH(submit_date)) as dummy
from data force index(IX_submit_date)
group by id, name, submit_date
having row_number <= 2;

你可以在这里测试它:http ://sqlfiddle.com/#!2/e829c /13(我对 2 个元素进行了剪切,而不是 1500)

于 2012-11-13T21:49:12.007 回答
1

我想你正在寻找一个GROUP BY条款。我需要知道更多才能给你一个明确的答案。但以下伪查询可能会引导您朝着正确的方向前进。

SELECT *, SUM(some_field) 
FROM data
GROUP BY MONTH(submit_date)

或者如果您只需要 1500 行,请选择按日期排序的前 1500 行

SELECT TOP(1500) *
FROM data
WHERE submit_date > '12-01-2012' AND submit_date < '11-01-2014'
ORDER BY MONTH(submit_date)

使用 MySQL,您可以使用LIMIT

SELECT *
FROM data
WHERE submit_date > '12-01-2012' AND submit_date < '11-01-2014'
ORDER BY MONTH(submit_date)
LIMIT 0,1500;
于 2012-11-13T21:27:26.483 回答
0

您几乎可以像拥有它一样进行操作,只需在查询之间添加一个 UNION 即可。但是您仍然必须每月创建 1 个查询。

否则,您需要枚举返回的行。您需要先订购并枚举您的记录,然后您可以对该选择进行选择以仅获得前 X。不确定是否要包括上个月。

SET @prev_date='';
SELECT * FROM (
SELECT IF(@prev_date=submit_date, @incr := @incr+1, @incr:=1) AS row_num, 
data.*, 
(@prev_date := submit_date) AS set_prev_date 
FROM data WHERE submit_date BETWEEN "2012-12-01" AND "2014-11-30" 
ORDER BY submit_date
) tmp WHERE row_num<1500;
于 2012-11-13T22:48:14.307 回答