问题
I was trying to reproduce the select top n from group SQL but access freezes (takes minutes to complete) even on small set of data.
date ret1 anndate
26-Jul-13 0.999214 25-Jul-13
29-Jul-13 0.982684 25-Jul-13
30-Jul-13 0.947938 25-Jul-13
31-Jul-13 1.024081 25-Jul-13
01-Aug-13 1.017739 25-Jul-13
02-Aug-13 1.001621 25-Jul-13
10-Dec-13 0.965405 09-Dec-13
11-Dec-13 1.009705 09-Dec-13
12-Dec-13 1.025508 09-Dec-13
13-Dec-13 0.994232 09-Dec-13
16-Dec-13 1.009065 09-Dec-13
17-Dec-13 0.984549 09-Dec-13
18-Dec-13 1.007299 09-Dec-13
What I wanted to achieve is to have the five following rows per each 'anndate'. for example, for anndate 25 july 2013, I want the first 5 rows. for anndate 09-dec-2013, I want 5 following rows ended on 16-dec-2013.
my code is:
SELECT *
FROM com
WHERE date in
(select top 5 date from com where com.date>com.anndate);
but it causes access to crash(correction: should be 'take minutes to complete'). Anyone can help point out where is wrong?
update:
I changed the column name [date] to [cdate], it still doesnt work.
I ran something simple like below and it still takes minutes to complete....
SELECT *
FROM com
WHERE cdate in (select cdate from com )
回答1:
I stored your sample data in a table with both date
and anndate
as Date/Time data type. Then I built a query with anndate_rank
generated from a correlated subquery. The purpose of anndate_rank
is a rank number within each anndate
group.
Then that entire query became a subquery in a new one which selects anndate_rank
<= the top limit --- I chose top 2 instead of top 5.
This is the result set from the query, and the query is below:
date ret1 anndate anndate_rank
---------- -------- --------- ------------
7/26/2013 0.999214 7/25/2013 1
7/29/2013 0.982684 7/25/2013 2
12/10/2013 0.965405 12/9/2013 1
12/11/2013 1.009705 12/9/2013 2
SELECT
sub.date,
sub.ret1,
sub.anndate,
sub.anndate_rank
FROM
(
SELECT
c.date,
c.ret1,
c.anndate,
(
SELECT Count(*)
FROM com AS c2
WHERE
c2.anndate=c.anndate
AND c2.date<=c.date
) AS anndate_rank
FROM com AS c
) AS sub
WHERE sub.anndate_rank<=2;
Note this approach assumes no repeated date
values within any anndate
group, as in your sample data. If your real data does include duplicate date
/ anndate
pairs, this query will not give you the results you want.
来源:https://stackoverflow.com/questions/26805394/sql-query-select-top-5-per-group-leading-access-to-freeze-on-simple-code-and-sma