我仍然开始涉足 SQL。我在查询日期并将它们分组时遇到问题。我想对日期进行分组。并从此日期显示特定日期范围内的访问名称和类型。
从下面的例子说,我想查询从01/01/2012 到 31/12/2012范围内访问的人,访问类型为4
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 ?))
你可以试试:
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;
按日期分组将为您提供每个唯一日期的一行,从您的示例输出来看,这看起来不像您想要的。
如果 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