选择多部电话的最近日期

时间:2019-02-27 14:19:38

标签: sql-server tsql

REQ:如果多部电话具有相同的最近日期,请以编号最少的电话。我的数据如下。

CustomerID PhoneNumber  CreatedDate

  1111      1234587        2013-09-10
  1111      1243557        2013-09-11
  1111      3214562        2009-12-01
  2222      7654312        2013-02-05
  2222      6544343        2006-07-23
  2222      7652135        2006-04-16
  2222      5672851        2010-11-16
  2222      4726722        1998-06-18

输出如下:

CustomerID  PhoneNumber  CreatedDate
 1111         1234587     2013-09-10
 2222         4726722     1998-06-18

4 个答案:

答案 0 :(得分:0)

使用两个子查询来确定最大日期和最小电话号码,并将它们与表格本身联系起来

SELECT a.CustomerID, a.PhoneNumber, a.CreatedDate
FROM test a
JOIN (SELECT CustomerID, MAX(CreatedDate) as max_date
      FROM test 
      GROUP BY CustomerID) b ON b.CustomerID = a.CustomerID AND
                                b.max_date = a.CreatedDate
JOIN (SELECT CustomerID, CreatedDate, MIN(PhoneNumber) min_number
      FROM test 
      GROUP BY CustomerID, CreatedDate) c ON c.CustomerID = a.CustomerID AND 
                                             c.min_number = a.PhoneNumber AND 
                                             c.CreatedDate = a.CreatedDate

答案 1 :(得分:0)

有帮助吗?

SELECT TOP 1 CreatedDate, MIN(CAST(PhoneNumber AS INT))
FROM [TABLENAME]
GROUP BY CAST(CreatedDate AS DATE)

答案 2 :(得分:0)

另一种选择是在<section class="page-section cta closeBorder"> <div class="container"> <div class="row"> <div class="col-xl-9 mx-auto"> <div class="cta-inner rounded"> <h2 class="section-heading mb-4"> <span class="text-center section-heading-upper">Wordt lid van de nieuwsbrief</span> <span class="text-center section-heading-lower">Blijf op de hoogte</span> </h2> <p class="mb-0 text-center">When you walk into our shop to start your day, we are dedicated to providing you with friendly service, a welcoming atmosphere, and above all else, excellent products made with the highest quality ingredients. If you are not satisfied, please let us know and we will do whatever we can to make things right!</p> <b class="pull-left"><em>E-mailadres:</em></b> <input type="email" class="form-control" name="email"> <input type="submit" class="btn-block subBtn" value="Abonneer!"> </div> </div> </div> </div> </section>的音乐会中使用WITH TIES子句

示例

Row_Number()

返回

Select Top 1 with ties *
 From  YourTable
 Order By Row_Number() over (Partition By CustomerID Order By CreatedDate Desc,PhoneNumber)

答案 3 :(得分:0)

尝试一下:

SELECT 
    YT.CreatedDate
    ,MIN(YT.PhoneNumber) 
FROM
    YourTable YT
GROUP BY
    YT.CreatedDate