存储过程仅显示每个关系代码1行

时间:2017-01-09 09:20:48

标签: sql sql-server tsql stored-procedures

我创建了一个存储过程,每个关系代码只显示最新的预订日期。现在我得到了这个:

USE [fms]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[spLoadNonBooking] (@DateFrom as DATE, @DateTill as DATE)
AS

BEGIN
    WITH NonBooking (Relationcode, Companyname, LatestBooking, LatestContact)
    AS
    (
        SELECT r.[RELATIONCODE], r.[COMPANYNAME], b.[BOOKINGDATE], c.[DATE]
        FROM [fms].[dbo].[Relation] r
        LEFT OUTER JOIN [fms].[dbo].[Booking] b
        ON b.[RELATIONCODE] = r.[RELATIONCODE]
        LEFT OUTER JOIN [fms].[dbo].[Communication] c
        ON c.[RELATIONCODE] = r.[RELATIONCODE]
        WHERE b.[BOOKINGDATE] < DATEADD(month, -2, GETDATE()) AND b.[BOOKINGDATE] > DATEADD(year, -1, GETDATE())
        GROUP BY r.[RELATIONCODE], r.[COMPANYNAME], b.[BOOKINGDATE], c.[DATE]
    )
    SELECT Relationcode, Companyname, LatestBooking, LatestContact FROM NonBooking
END

但是目前显示的数据是这样的:

enter image description here

所以它显示了每个预订的一行,但是我希望每个关系代码都有1行与LATEST预订日期,但我不知道如何做到这一点,有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

使用Row_Number()&amp; Top 1 with ties

SELECT TOP 1 WITH ties Relationcode,
                       Companyname,
                       LatestBooking,
                       LatestContact
FROM   NonBooking
ORDER  BY Row_number() OVER(partition BY relationcode ORDER BY LatestBooking DESC) 

如果RELATIONCODE表中的Relation是唯一的,那么这是使用Outer Apply的一种方法。在我看来更好的方法

SELECT r.[RELATIONCODE],
       r.[COMPANYNAME],
       oa.[BOOKINGDATE],
       oa.[DATE]
FROM   [fms].[dbo].[Relation] r
       OUTER apply (SELECT TOP 1 b.[BOOKINGDATE],
                                 c.[DATE]
                    FROM   [fms].[dbo].[Booking] b
                           LEFT OUTER JOIN [fms].[dbo].[Communication] c
                                        ON c.[RELATIONCODE] = r.[RELATIONCODE]
                    WHERE  b.[BOOKINGDATE] < Dateadd(month, -2, Getdate())
                           AND b.[BOOKINGDATE] > Dateadd(year, -1, Getdate())
                           AND b.[RELATIONCODE] = r.[RELATIONCODE]
                    ORDER  BY b.[BOOKINGDATE] DESC) oa