"失落" SQL Server中的客户

时间:2017-08-17 10:30:30

标签: sql sql-server

我有一个问题,管理层希望看到"丢失"顾客。丢失的客户是指在最后 4个月内没有订购的客户。

结果应按实体编号:

+------------------------+---------+
|         Method         |  Time   |
+------------------------+---------+
| nested loops, (-i-j)%2 | 1500 ms |
| nested loops,  (i+j)%2 |  500 ms |
| nested loops,  (i^j)&1 |  500 ms |
| manual filling         |    2 ms |
| padStart()             |    1 ms |
+------------------------+---------+

有3张桌子。

  • tblOrder包含最后一个orderdate。
  • tblRelation包含所有关系/客户
  • tblsysentity,其中包含实体编号

每个关系(客户)都连接到关系表中的实体。

2 个答案:

答案 0 :(得分:0)

我编写了连接属性,因为你没有提供它们。我假设tblRelationtblOrder之间存在1:N的关系。我省略tblsysentity,因为它似乎没有相关性。

SELECT *
FROM tblRelation 
WHERE tblRelation.cid NOT IN
(
    SELECT cid FROM tblOrder o
    WHERE orderdate > DATEADD(month, -4, GETDATE())
)

也可以使用NOT EXISTSEXCEPT

SELECT *
FROM tblRelation 

EXCEPT

SELECT c.*
FROM tblRelation c
JOIN tblOrder o ON c.cid = o.cid
WHERE orderdate > DATEADD(month, -4, GETDATE())

答案 1 :(得分:0)

没有样本数据很难提供解决方案,但总的来说,你可以尝试这样的事情:

with
-- first get lost customers
max_orderDates as (
select
   customerID
  ,max(orderDate) max_orderDate
from tblOrder o
group by customerID
having DATEADD(month, 4, max(orderDate)) < GETDATE()
)
-- now link customers with entity, and count number of lost customers per entity
select
   e.entityID as Entity
  ,count(1) as [Lost Customers]
from max_orderDates lost_c

-- join to relation
left join tblRelation rel
  on lost_c.customerID = rel.customerID

-- join to entity
left join tblsysentity e
  on rel.entityID = e.entityID

group by
   e.entityID