SQL根据ID,DataLoad日期生成IsNew列

时间:2017-05-08 10:06:36

标签: sql sql-server

我正在尝试创建一个SQL视图,并且在根据ID和报告日期字段导出IsNew(布尔)列时遇到问题。我想在select查询中编写CASE语句。我的数据如下:

 ReportingDate  ID
02/09/2016  392
02/09/2016  393
02/09/2016  394
09/09/2016  394
09/09/2016  400
16/09/2016  400
16/09/2016  407

我想为上面的数据导出IsNew(布尔)列,以查看ID字段是否第一次出现。例如:ID:407日期:2016年9月16日是新创建的,因为我无法在之前的reportdate中找到相同的ID。而ID:400不是新创建的,因为在以前的加载中存在:09/09/2016。

我希望输出类似这样:任何建议都非常受欢迎。

 ReportingDate  ID  IsNew
02/09/2016  392 TRUE
02/09/2016  393 TRUE
02/09/2016  394 TRUE
09/09/2016  394 FALSE
09/09/2016  400 TRUE
16/09/2016  400 FALSE
16/09/2016  407 TRUE

3 个答案:

答案 0 :(得分:2)

您可以使用row_number来获取此信息:

scanf()

您的输入表:

select *,
    case 
        when Row_Number() over (
                partition by ID 
                order by ReportingDate
                ) = 1
            then 'TRUE'
        else 'FALSE'
        end as IsNew
from yourtable

结果:

create table #yourreporting (ReportingDate date, ID int)

Insert into #yourreporting
(    ReportingDate  , ID ) values
 ('09-02-2016',  392)
,('09-02-2016',  393)
,('09-02-2016',  394)
,('09-09-2016',  394)
,('09-09-2016',  400)
,('09-16-2016',  400)
,('09-16-2016',  407)

答案 1 :(得分:0)

您可以加入同一张桌子并查找匹配项或null s:

select a.ID
      ,case when b.ID is null then 1 else 0 end as IsNew
from YourTable a
    left join (select ID
                     ,max(ReportingDate) as MaxReportingDate
               from YourTable
               group by ID
              ) b
        on(a.ID = b.ID
           and a.ReportingDate < b.ReportingDate
          )

根据您的可读性偏好,您也可以CTE

执行此操作
with c as
(
    select ID
          ,max(ReportingDate) as MaxReportingDate
    from YourTable
    group by ID
)
select a.ID
      ,case when b.ID is null then 1 else 0 end as IsNew
from YourTable a
    left join c
        on(a.ID = c.ID
           and a.ReportingDate < c.ReportingDate
          )

答案 2 :(得分:0)

您可以使用Window函数和Subquery

来完成

<强>架构:

CREATE TABLE #TAB (ReportingDate DATE, ID INT)

INSERT INTO #TAB
SELECT CONVERT(DATE,'02/09/2016',103) , 392 
UNION ALL
SELECT CONVERT(DATE,'02/09/2016',103) , 393 
UNION ALL
SELECT CONVERT(DATE,'02/09/2016',103) , 394 
UNION ALL
SELECT CONVERT(DATE,'09/09/2016',103) , 394 
UNION ALL
SELECT CONVERT(DATE,'09/09/2016',103) , 400 
UNION ALL
SELECT CONVERT(DATE,'16/09/2016',103) , 400 
UNION ALL
SELECT CONVERT(DATE,'16/09/2016',103) , 407 

现在选择如下

SELECT ReportingDate
    ,ID
    ,CASE WHEN SNO = 1 THEN 'TRUE' ELSE 'FALSE' END AS IsNew
FROM (
    SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ReportingDate) AS SNO
        ,ReportingDate,ID
    FROM #TAB
    ) A

<强>结果

+---------------+-----+-------+
| ReportingDate | ID  | IsNew |
+---------------+-----+-------+
| 2016-09-02    | 392 | TRUE  |
| 2016-09-02    | 393 | TRUE  |
| 2016-09-02    | 394 | TRUE  |
| 2016-09-09    | 394 | FALSE |
| 2016-09-09    | 400 | TRUE  |
| 2016-09-16    | 400 | FALSE |
| 2016-09-16    | 407 | TRUE  |
+---------------+-----+-------+