客户维度

时间:2019-03-07 15:57:51

标签: sql sql-server

我正在编写SQL代码以创建客户维度。

ID Name File Import Date
1   XXX  12/30/2018
1   XXX  12/31/2018
1   XXX  1/1/2019
1   YYY  2/2/2019
1   YYY  3/2/2019
1   YYY  4/2/2019
2   AAA  1/1/2019

我想创建一个查询,在其中可以捕获不同的名称以及历史记录

新表格

ID Name     Active
1  XXX        0
1  YYY        1
2  AAA        1

下面的查询给我最新的记录

SELECT Distinct a.[ID] as CustID
,a.[Name] as CustName
FROM X as a 
inner join 
(select ID,[MaxDate] = MAX(FileImportDate) from X  group by ID   ) b 
on a.ID = b.ID 
and a.FileImportDate = b.MaxDate`

在此处输入代码。

2 个答案:

答案 0 :(得分:1)

我要咬...

通过评论,这是一个猜测

示例

Select Top 1 with ties
       ID
      ,Name
      ,Active = case when [FileImportDate] = max([FileImportDate]) over (Partition By ID) then 1 else 0 end
From  YourTable
Order By Row_Number() over (Partition By Name Order by [FileImportDate] Desc)

返回

ID  Name    Active
2   AAA     1
1   XXX     0
1   YYY     1

这里是dbFiddle

答案 1 :(得分:0)

使用distinctcase

select 
  distinct t.id, t.name,
  case 
    when exists (
      select 1 from tablename 
      where 
        id = t.id 
        and name <> t.name 
        and fileimportdate > t.fileimportdate) then 0 
    else 1 
  end active
from tablename t

请参见demo 结果:

id  name    active
1   XXX       0
1   YYY       1
2   AAA       1