我对sql查询有疑问。在这种情况下,我需要获取最近历史活动是14天前的用户,但我的历史记录是空的,我可以做如下操作:如果电子邮件历史记录在第14天是空的,则选择没有电子邮件历史记录
SELECT st.id, st.firstName, st.lastName, st.email, st.lastLogin, st.phone, st.gender, sa.title,bra.Title as brand, ss.SaleDate, teh.sDate, sa.imageUrl, sa.guid, st.mallId, sa.id saleId
FROM dbo.Users st
INNER JOIN KEY_SalesToUsers ss ON (st.ID=ss.userID)
INNER JOIN Sales sa ON (sa.ID=ss.SaleID)
INNER JOIN Brands bra ON (sa.BrandID=bra.ID)
INNER JOIN dbo.UserEmailHistory teh ON st.id = teh.userId
WHERE CONVERT(date,DATEADD(day,1,ss.SaleDate))= CONVERT(date,getdate())
AND teh.sDate >= dateadd(dd,-14,getdate())
AND teh.sDate <= dateadd(dd,-13,getdate())
AND sDate <= dateadd(dd,-1,getdate())
ORDER BY ss.SaleDate DESC
答案 0 :(得分:1)
而不是
INNER JOIN dbo.UserEmailHistory teh ON st.id = teh.userId
尝试使用
LEFT OUTER JOIN dbo.UserEmailHistory teh ON st.id = teh.userId
答案 1 :(得分:1)
您应该再次阅读LEFT JOIN和INNER JOIN差异,还必须更改where条件。您无需通过&lt;&gt;进行检查两次。如果这一天对于您将日期转换为日期格式很重要,然后进行检查。表现会增加。
答案 2 :(得分:0)
SELECT st.id, st.firstName, st.lastName, st.email, st.lastLogin, st.phone, st.gender, sa.title,bra.Title as brand, ss.SaleDate, teh.sDate, sa.imageUrl, sa.guid, st.mallId
FROM dbo.Users st
INNER JOIN KEY_SalesToUsers ss ON (st.ID=ss.userID)
INNER JOIN Sales sa ON (sa.ID=ss.SaleID)
INNER JOIN Brands bra ON (sa.BrandID=bra.ID)
LEFT OUTER JOIN dbo.UserEmailHistory teh ON st.id = teh.userId
WHERE CONVERT(date,DATEADD(day,1,ss.SaleDate))=CONVERT(date,getdate())
AND IsNull(sDate, '') = '' OR CONVERT(date,DATEADD(day,14,teh.sDate))=CONVERT(date,getdate())
ORDER BY ss.SaleDate DESC