我需要在2012年12月到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查询编写得更小?
答案 0 :(得分: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个)
答案 1 :(得分:1)
我认为你正在寻找一个GROUP BY
条款。我需要知道更多,以给你一个明确的答案。但是下面的pseduo查询可能会指导您朝着正确的方向发展。
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;
答案 2 :(得分: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;