[英]SQL Query to find Customers who order exact same order list more than once in 2 months
[英]sql query to find customers who order too frequently?
我的數據庫實際上不是客戶和訂單,它是客戶和眼科測試的處方(以防萬一有人想知道為什么我希望我的客戶不那么頻繁地下訂單!)
我有一個眼鏡商鏈數據庫,處方表有分支ID號,患者ID號和他們測試眼睛的日期。 隨着時間的推移,患者將在數據庫中列出多個眼睛測試。 如何獲得六個月內在系統上輸入一次以上處方的患者名單。 換言之,例如,一個處方的日期是在同一患者的先前處方的日期之后的三個月內。
樣本數據:
Branch Patient DateOfTest
1 1 2007-08-12
1 1 2008-08-30
1 1 2008-08-31
1 2 2006-04-15
1 2 2007-04-12
我不需要知道結果集中的實際日期,也不需要完全是三個月,只是一個處方太接近以前處方的患者列表。 在給出的示例數據中,我希望查詢返回:
Branch Patient
1 1
這種查詢不會經常運行,所以我不會過分擔心效率問題。 在我們的實時數據庫中,我在處方表中有25萬條記錄。
像這樣的東西
select p1.branch, p1.patient
from prescription p1, prescription p2
where p1.patient=p2.patient
and p1.dateoftest > p2.dateoftest
and datediff('day', p2.dateoftest, p1.dateoftest) < 90;
應該......你可能想補充一下
and p1.dateoftest > getdate()
限制未來的測試處方。
這個將有效地使用你當然應該擁有的(Branch, Patient, DateOfTest)
索引:
SELECT Patient, DateOfTest, pDate
FROM (
SELECT (
SELECT TOP 1 DateOfTest AS last
FROM Patients pp
WHERE pp.Branch = p.Branch
AND pp.Patient = p.Patient
AND pp.DateOfTest BETWEEN DATEADD(month, -3, p.DateOfTest) AND p.DateOfTest
ORDER BY
DateOfTest DESC
) pDate
FROM Patients p
) po
WHERE pDate IS NOT NULL
在途中:
select d.branch, d.patient
from data d
where exists
( select null from data d1
where d1.branch = d.branch
and d1.patient = d.patient
and "difference (d1.dateoftest ,d.dateoftest) < 6 months"
);
這部分需要改變 - 我不熟悉SQL Server的日期操作:
"difference (d1.dateoftest ,d.dateoftest) < 6 months"
自聯接:
select a.branch, a.patient
from prescriptions a
join prescriptions b
on a.branch = b.branch
and a.patient = b.patient
and a.dateoftest > b.dateoftest
and a.dateoftest - b.dateoftest < 180
group by a.branch, a.patient
這假設您希望兩次訪問同一分支的患者。 如果不這樣做,請取出分支部分。
SELECT Branch
,Patient
FROM (SELECT Branch
,Patient
,DateOfTest
,DateOfOtherTest
FROM Prescriptions P1
JOIN Prescriptions P2
ON P2.Branch = P1.Branch
AND P2.Patient = P2.Patient
AND P2.DateOfTest <> P1.DateOfTest
) AS SubQuery
WHERE DATEDIFF(day, SubQuery.DateOfTest, SubQuery.DateOfOtherTest) < 90
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.