[英]How to compare dates for multiple rows under the same table and same account
如果有任何SQL專家可以為我指出正確的方向,那將是巨大的幫助。 我正在學習SQL,並想創建一個報告,該報告將在相同的“個人ID”下生成帳戶編號,彼此之間<= 30天,並且排除任何其他帳戶。 所有需要的信息都在同一張表中。
例如,下面的代碼將列出一個具有多個帳戶編號的具有相同人員編號的人員及其創建日期:
select accounttid, creationdate, personid from Table1 where personid in (
select (personid) from Table1 group by personid having COUNT (accountid) > 1)
EXAMPLE RESULT:
accountid creationdate personid
5501624 2013-05-01 101
5501544 2013-05-03 101
5510220 2013-10-24 10337
5504204 2013-06-27 10337
5502332 2013-05-21 1047
5502628 2013-05-28 1047
5508844 2013-10-01 1047
不知道從這里去哪里。 然后,我想獲取這些Accountid,並以某種方式比較Creationdate的差異,該差異小於或等於30天,但僅當PersonID相同時才進行比較。
我將使用半聯接:
select accountid, creationdate, personid
from Table1 t1
where EXISTS(
SELECT 1 FROM Table1 t2
WHERE t1.personid = t2.personid
AND t1.accountid <> t2.accountid
AND t1.creationdate BETWEEN
t2.creationdate - interval 30 day
AND
t2.creationdate + interval 30 day
);
演示-> http://www.sqlfiddle.com/#!2/2be93/2
-編輯-
在SQL Server上,請使用以下條件:
BETWEEN dateadd( day, -30, t2.creationdate )
AND
dateadd( day, 30, t2.creationdate )
這是對SQL Server的查詢:
select accountid, creationdate, personid
from Table1 t1
where EXISTS(
SELECT 1 FROM Table1 t2
WHERE t1.personid = t2.personid
AND t1.accountid <> t2.accountid
AND t1.creationdate BETWEEN
dateadd( day, -30, t2.creationdate )
AND
dateadd( day, 30, t2.creationdate )
);
演示:----> http://www.sqlfiddle.com/#!3/cc922/4
對您的查詢的一些評論:
select accountid, creationdate, personid
from Table1
where personid in (
select personid
from Table1
group by personid
having COUNT(accountid) > 1
);
想一會兒...具有HAVING COUNT
的子查詢必須為每個人計算多個記錄-它必須讀取整個表(所有行)以獲得此信息,因為我們要求give me a number of rows for given person
。 如果此人有10.000個帳戶,我們需要閱讀所有帳戶以進行計數。
但是,我們不需要此信息,也不需要閱讀整個表。 我們需要的是這個問題的答案: if this person has at least 2 accounts
。
對於這種查詢,我們可以使用EXISTS
運算符:
select accountid, creationdate, personid
from Table1 t1
where EXISTS(
SELECT 1 FROM Table1 t2
WHERE t1.personid = t2.personid
AND t1.accountid <> t2.accountid
);
在此查詢中,MySql不需要計數所有記錄,也不需要讀取整個表。 當找到滿足EXISTS運算符內的子查詢定義的條件的第一條記錄時,它將停止讀取表。
select distinct(personid, accountID)
from Table1
where Table1 personid in
(
select distinct(t1a.personid)
from Table1 as t1a
join Table1 as t1b
on t1a.personid = t1b.personid
and t1a.creationdate < t1b.creationdate
and datediff(dd, t1a.creationdate, t1b.creationdate) <= 30
)
可能您可以基於personid
應該相同並且兩個creationdate
之間的差異大於30天的條件來加入自己獲得的結果。
就像是:
{select accounttid, creationdate, personid
from Table1 where personid in (
select (personid)
from Table1
group by personid
having COUNT (accountid) > 1)} as a
join
{select accounttid, creationdate, personid from
Table1 where personid in (
select (personid) from
Table1
group by personid
having COUNT (accountid) > 1)} as b
on a.personid=b.personid and a.creationdate-b.creationdate >= 30
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.