SQL:获取具有最少日期的行+使用带有select语句

时间:2016-09-26 19:31:11

标签: sql sql-server tsql greatest-n-per-group

我有一个包含3列( id 类型日期)的表格,其中包含以下值:

id    type    date
---   ---      ---
191     0    2016-09-15 11:26:51.000
191     1    2016-09-15 11:30:31.000
200     0    2016-09-15 17:36:19.000
200     1    2016-09-15 18:26:51.000
331     0    2016-09-16 07:26:22.000

这就是我想要做的事情:

对于上面的每个ticketid,选择最小日期最少的行。一旦完成,我想在我的输出中另一个名为“isEngaged”的列,如果ticketid的任何记录都有一个type = 1,它将被设置为1。

我想要的输出:

id    type    date                        isEngaged
---   ---      ---                         ---
191     0    2016-09-15 11:26:51.000        1
200     0    2016-09-15 17:36:19.000        1
331     0    2016-09-16 07:26:22.000        0

这是我到目前为止所做的:(这需要只返回最少日期的行)

SELECT id, type, date FROM (SELECT ROW_NUMBER() OVER (PARTITION BY id ORDER BY date ASC) AS [Row], id, type, date)
      FROM mytable WHERE type IN (0)) WHERE [Row] = 1

真的不确定如何合并isEngaged部分。我试图使用CASE WHEN但不确定如何继续这样做:

SELECT id, type, date,
"isEngaged" = CASE WHEN (SELECT * FROM mytable where type in (1) and id = <not sure what to put here>) THEN 1 ELSE 0 END
FROM mytable

如果您知道更好的方法,请告诉我。

2 个答案:

答案 0 :(得分:3)

如果您只接受0/1列中的type值,则可以使用MAX()作为窗口函数。

SELECT  
  id, type, date, isEngaged
FROM (
  SELECT
    id, type, date,
    MAX(type) OVER (PARTITION BY id) AS isEngaged
    ROW_NUMBER() OVER (PARTITION BY id ORDER BY date) AS rn
  FROM mytable
  ) t
WHERE rn = 1

如果您接受高于1的值,那么CASE中适当的MAX()语句就足够了:

SELECT  
  id, type, date, isEngaged
FROM (
  SELECT
    id, type, date,
    MAX(CASE WHEN type = 1 THEN 1 ELSE 0 END) OVER (PARTITION BY id) AS isEngaged
    ROW_NUMBER() OVER (PARTITION BY id ORDER BY date) AS rn
  FROM mytable
  ) t
WHERE rn = 1

答案 1 :(得分:0)

select
id,
case when sum_engaged > 0 then 1 else 0 end as isEngaged,
min_date
from
(SELECT id, 
sum(case when type IN( 1,3) then 1 else 0 end) as sum_engaged, min(date) as min_date 
FROM mytable 
group by id) g