SQL SERVER 2008.如何仅根据日期选择一行

时间:2017-07-06 10:41:31

标签: sql-server-2008

std::vector

以上是上述脚本输出的片段,但并未提供所需的输出。我想只为每个CustID&来自我的数据集的CustAtt基于appdate列。

所需的输出应包括当前日期的下一个最早的日期,如果日期相同,则任何给定的行都可以接受: 输出表应该产生:

Select MIN([appdate]), CustID, CustAtt, Surname, Firstname, itemType
From table 
Where appDate > (getdate())
Group by CustID, CustAtt

CustAtt CustID  Surname Firstname   appDate      itemType
 53247   20675    A        AX       
 49535   12/FX08  B        BX      14/08/2017     solid
 70433   400039   C        CX       
 67119   413555   D        DX       
 51406   27/EY07  E        EX      14/07/2017     Liquid
 51406   27/EY08  E        EX      13/09/2017     Gas
 51406   27/EY09  E        EX      11/12/2017     Solid A
 51406   27/EY10  E        EX      06/06/2018     Liquid A
 82820   410053   F        FX       
 52395   29/FA72  G        GX      25/09/2017     Gas A
 89488   414282   H        HX       
 55855   412799   I        IX      30/08/2017     Solid 
 55855   412799   I        IX      21/08/2017     Liquid
 53248   16/EK15  J        JX      06/07/2017     Gas
 53248   16/EK15  J        JX      17/07/2017     Solid B
 89835   911528   K        KX      08/05/2018     Solid B 

2 个答案:

答案 0 :(得分:0)

示例:http://sqlfiddle.com/#!6/c35e2/1

create table t(
    id int,
    x int,
    y int,
    z int,
    a int,
    b int,
    c datetime
);


-- Build t table
INSERT INTO t values
(1, 1, 2, 3, 4, 5, getdate()),
(2, 1, 2, 3, 4, 5, dateadd(hh,+3,getdate())),
(3, 1, 2, 3, 4, 5, dateadd(hh,+1,getdate())),
(4, 1, 2, 3, 4, 5, dateadd(hh,+2,getdate())),
(5, 1, 2, 3, 4, 5, dateadd(hh,-2,getdate())),
(6, 1, 2, 3, 4, 5, dateadd(hh,-1,getdate())),
(7, 1, 2, 3, 4, 5, dateadd(hh,+1,getdate())),
(8, 1, 2, 3, 4, 5, dateadd(hh,+1,getdate())),
(9, 1, 2, 3, 4, 5, dateadd(hh,+1,getdate()));

select top 1 t.id, s.*, t.c 
from t
join (
    select x,y,z,a,b
    from t
    group by x,y,z,a,b
    having count(*) > 1
) s 
on s.x = t.x
    and s.y = t.y
    and s.z = t.z
    and s.a = t.a
    and s.b = t.b
    and (getdate() < t.c)
order by t.c

答案 1 :(得分:0)

您必须使用HAVING关键字。它可以过滤&#34;在&#34;。

之后
SELECT
 MIN([appdate]), 
 id, 
 type
FROM
 [table]
WHERE
 appdate > GETDATE()
GROUP BY
 id, type
HAVING 
  COUNT(*) > 1 -- select only records, that have duplicates, based on our "group by"
ORDER BY
 id

已添加12.07.17: (修改后的问题)

计算行号(按CustID&amp; CustAtt分类,按appDate排序),然后为每一行选择第一行。

;WITH cte AS (
    SELECT
        *, 
        Row_number() OVER( 
          PARTITION BY CustID, CustAtt ORDER BY appDate
        ) row_number
    FROM
        table
    ) 
SELECT
  * 
FROM
  cte
WHERE
  row_number = 1