I have a table named tblOrders
| ID | name | email | amount | date |
+-----+---------+------------+---------+------------+
| 1 | danny | dan@email | $10.00 | 06/01/2015 |
| 2 | bryan | bra@email | $50.00 | 06/01/2015 |
| 3 | jenny | jen@email | $20.00 | 06/02/2015 |
| 4 | gabby | gab@email | $35.00 | 06/02/2015 |
| 5 | lisa | lisa@email | $12.00 | 06/03/2015 |
| 6 | don | don@email | $23.00 | 06/04/2015 |
| 7 | danny | dan@email | $22.00 | 06/04/2015 |
| 8 | bryan | bra@email | $55.00 | 06/05/2015 |
| 9 | danny | dan@email | $69.00 | 06/20/2015 |
| 10 | danny | dan@email | $49.00 | 06/25/2015 |
I want to select from tblOrders
between date 06/03/2015
and 06/25/03/2015
and then count the number of repeated customers I have.
Select between date 06/03/2015
and 06/25/03/2015
provides
| ID | name | email | amount | date |
+----+-------+------------+--------+-------------+
| 5 | lisa | lisa@email | $12.00 | 06/03/2015 |
| 6 | don | don@email | $23.00 | 06/04/2015 |
| 7 | danny | dan@email | $22.00 | 06/04/2015 |
| 8 | bryan | bra@email | $55.00 | 06/05/2015 |
| 9 | danny | dan@email | $69.00 | 06/20/2015 |
| 10 | danny | dan@email | $49.00 | 06/25/2015 |
Then checking by email
from those records if exist in all tblOrders
and count
This should provide count of 2
as there are 2 customers between those dates that ordered before.
How can I achieve that with one SQL query?
I'm using Access database and ASP classic
My current code is
ReturnCustomers = 0
Set rs = Server.CreateObject("ADODB.Recordset")
SQL = ("select ID,Email,OrderDate from tblOrders Where OrderDate between #"&date1&"# and "&date2&";")
rs.Open SQL,Cnn,3,1
Do while Not rs.EOF
Set rsCount = Server.CreateObject("ADODB.Recordset")
SQL = ("select ID from tblOrders Where Email='"&rs("Email")&"' and Not ID="&rs("ID")&";")
rsCount.Open SQL,Cnn,3,1
IF Not rsCount.EOF Then
ReturnCustomers = ReturnCustomers+1
End IF
rsCount.Close
Set rsCount = Nothing
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
response.write ReturnCustomers
How can I do this one in 1 SQL query?
答案 0 :(得分:1)
您似乎想要回头客 - 那些在目标日期范围内进行购买并在该日期范围开始前的某个时间进行购买的客户。
首先创建一个查询以检索这些唯一客户:
SELECT DISTINCT o1.email
FROM
tblOrders AS o1
INNER JOIN tblOrders AS o2
ON o1.email = o2.email
WHERE
(o1.date Between #2015-6-3# And #2015-6-25#)
AND o2.date < #2015-6-3#;
然而,您实际上只想要那些客户的数量。因此,您可以将第一个查询用作子查询,并从中获取计数:
SELECT Count(sub.email) AS CountOfemail
FROM
(
SELECT DISTINCT o1.email
FROM
tblOrders AS o1
INNER JOIN tblOrders AS o2
ON o1.email = o2.email
WHERE
(o1.date Between #2015-6-3# And #2015-6-25#)
AND o2.date < #2015-6-3#
) AS sub;
答案 1 :(得分:0)
你不是在寻找重复的东西。如果您想知道谁在#06/03/2015#到#06/25/03/2015#之间订购并在#06/03/2015#之前订购,您的查询应该是:
select distinct name, email from tblorders o
where date >=#06/03/2015# and date < #06/25/03/2015#
and exists (select * from tblorders p where p.email = o.email
and p.date <#06/03/2015# )
另请指定您的sql系统。