如何解决以下SQL问题

时间:2018-04-03 13:23:12

标签: sql sql-server sql-server-2008

我有一个名为t1的表,以下是该表中的数据

ID   DATE          INDEX
1    2015-12-13    N
1    2016-10-13    Y
1    2018-04-03    N
2    2004-12-13    N
2    2018-04-03    N

对于今天的日期我有ID 1的索引N但是对于相同的ID,我已经将索引Y也用于其他日期,而对于今天的ID 2,我们有索引N和Y找不到该ID的索引。

我正在寻找的输出应该是这样的

ID    DATE       INDEX   Final Date
1    2018-04-03    N     2016-10-13
2    2018-04-03    N     2018-04-03
  • 输出应该只包含两行,因为有两个不同的ID日期
  • index应仅包含今天的日期值
  • 但最终日期列应包含其他日期,如果我们之前有Y索引,那么其他日期将出现在那里

3 个答案:

答案 0 :(得分:2)

试试这个:

DECLARE @Table TABLE(ID INT, DATE DATE,[INDEX] VARCHAR(5))
INSERT into @Table values(1,'2015-12-13','N')
INSERT into @Table values(1,'2016-10-13','Y')
INSERT into @Table values(1,'2018-04-03','N')
INSERT into @Table values(2,'2004-12-13','N')
INSERT into @Table values(2,'2018-04-03','N')

SELECT id
    , CAST(GETDATE() AS DATE)DATE
    ,MAX(CASE WHEN DATE = CAST(GETDATE() AS DATE) THEN [INDEX] END)[INDEX]
    ,ISNULL(MAX(CASE WHEN [INDEX] = 'Y' THEN DATE END),CAST(GETDATE() AS DATE))[Final Date]
FROM @Table
GROUP BY id

<强>输出:

id  DATE      INDEX Final Date
1   2018-04-03  N   2016-10-13
2   2018-04-03  N   2018-04-03

答案 1 :(得分:1)

编辑:已针对错过的FinalDate进行了更正。现在也对相同的日期Y / N进行排序,并计算最终日期而不是今天的日期。

SQL Fiddle

MS SQL Server 2017架构设置

CREATE TABLE t1 ( ID int, dt date, idx varchar(1) ) ;
INSERT INTO t1 (ID, dt, idx) 
VALUES 
    ( 1,'2015-12-13','N')
  , ( 1,'2016-10-13','Y')
  , ( 1,'2018-04-03','N')
  , ( 2,'2004-12-13','N')
  , ( 2,'2018-04-03','N')
  , ( 3,'2018-01-03','N')
  , ( 3,'2018-01-05','Y')
  , ( 3,'2018-01-05','N')
;

查询1

SELECT s1.ID, s1.dt, s1.idx--, s1.rn, t1.*
  , CASE WHEN t1.idx = 'Y' THEN t1.dt ELSE s1.dt END AS finalDate
FROM (
  SELECT ID, dt, idx
    , ROW_NUMBER() OVER (PARTITION BY ID ORDER BY dt DESC, idx DESC) AS rn
  FROM t1
) s1
LEFT OUTER JOIN t1 ON s1.ID = t1.ID
  AND t1.idx = 'Y'
WHERE s1.rn = 1

<强> Results

| ID |         dt | idx |  finalDate |
|----|------------|-----|------------|
|  1 | 2018-04-03 |   N | 2016-10-13 |
|  2 | 2018-04-03 |   N | 2018-04-03 |
|  3 | 2018-01-05 |   Y | 2018-01-05 |

答案 2 :(得分:1)

这是一个很好的方法,无需变量就可以做到这一点(替换你的表名和列):

select col1 id,  col2 startdate, col3 [index],
case when exists(select 1 from #temp a where a.col1=b.col1 and a.col3='y') then (select col2 from #temp a where a.col1=b.col1 and a.col3='y' )else cast(getdate() as date) end enddate
from #temp b 
where col2=cast(getdate() as date)