查询涉及多个日期

时间:2013-10-17 13:38:31

标签: sql date grouping

我仍然开始尝试使用SQL。我在查询日期和分组时遇到问题。我想把日期分组。此日期显示特定日期范围内的姓名,访问类型。

从下面的示例中说,我想查询从 01/01/2012到2012年12月31日范围内访问过的人以及 4的访问类型

Sample table is attached

3 个答案:

答案 0 :(得分:1)

SELECT DISTINCT NAME 
FROM YOUR_tABLE 
WHERE (TYPE_OF_VISIT = 4) AND (DATE_OF_VISIT BETWEEN ? AND ?)

如果您希望第一次访问此范围内的每个客户,那么您应该尝试这样的

SELECT DISTINCT T1.NAME, T1.DATE_OF_VISIT 
FROM YOUR_TABLE T1
WHERE (T1.TYPE_OF_VISIT = 4) AND (T1.DATE_OF_VISIT BETWEEN ? AND ?)
AND T1.DATE_OF_VISIT = 
(SELECT MIN (T2.DATE_OF_VISIT) FROM YOUR_TABLE T2 WHERE T1.NAME=T2.NAME AND 
(T2.DATE_OF_VISIT BETWEEN ? AND ?))

答案 1 :(得分:0)

你可以尝试:

select Name, Type_of_visit
from Appointment_table
where Date_of_visit between '2012-01-01 00:00:00' and '2012-12-31 23:59:59'
and Type_of_visit = 4;

如果您想对结果进行分组(以及汇总访问次数):

select Name, Type_of_visit, COUNT(Type_of_visit) as Total_visits
from Appointment_table
where Date_of_visit between '2012-01-01 00:00:00' and '2012-12-31 23:59:59'
and Type_of_visit = 4
group by Name, Type_of_visit;

按日期分组会为每个唯一日期提供一行,从您的示例输出中看起来不像您想要的那样。

答案 2 :(得分:0)

如果列Date_of_visit不包含任何时间部分(即仅限日期)。您可以执行以下

SELECT NAME, TYPE_OF_VISIT
FROM appointment 
WHERE Type_of_visit = 4 
AND Date_of_visit >= '01/01/2012 ' 
AND Date_of_visit <= '31/12/2012'
GROUP BY NAME