這是一個措辭不妙的標題,但我不能拿出更好的東西,對不起!找到每個顧客的第二個約會日期
我們有一個表,從而有效地看起來像這樣(修剪爲簡潔起見):
create table Appointment (
AppointmentId int not null identity(1, 1),
CustomerId int not null,
AppointmentDate date not null,
constraint PK_Appointment primary key (AppointmentId),
constraint FK_Appointment_Customer foreign key (CustomerId) references Customer(CustomerId)
)
我們試圖寫一個發現誰曾內他們第二任命所有客戶的詳細資料查詢給定的日期範圍。請注意,客戶可能在同一天有兩次約會。我們可以使用幾個CTE來做到這一點,但我確定有更好的方法(可能使用某種類型的row_number類型函數?)。有什麼建議麼?我真的不喜歡我們的解決方案的事情是,它完全不靈活(當他們想要在給定的日期範圍內看到THIRD約會等等時會發生什麼)。
無論如何;這裏是我們想出的:
declare @startDate date = '2011-12-01'
declare @endDate date = '2011-12-31'
;
-- Limit to appointments before the end date
with AppointmentDates as (
select
AppointmentId,
CustomerId,
AppointmentDate
from
Appointment
where
AppointmentDate < @endDate
),
-- Get first appointment date - careful to cater for customers who have had
-- two appointments on the same day
FirstAppointments as (
select
CustomerId,
Min(AppointmentId) AppointmentId,
Min(AppointmentDate) AppointmentDate
from
AppointmentDates
group by
CustomerId
),
-- Second appointment date
SecondAppointments as (
select
AppointmentDates.CustomerId,
Min(AppointmentDates.AppointmentId) AppointmentId,
Min(AppointmentDates.AppointmentDate) AppointmentDate
from
AppointmentDates
inner join FirstAppointments on AppointmentDates.CustomerId = FirstAppointments.CustomerId
where
AppointmentDates.AppointmentId > FirstAppointments.AppointmentId
group by
AppointmentDates.CustomerId
having
Min(AppointmentDates.AppointmentDate) > @startDate
)
-- Bulk of query goes here; trimmed for brevity
select * from SecondAppointments
這是我以後的,謝謝! – gerrod 2012-01-03 00:51:01