帮助查询只应返回最近的记录

时间:2011-05-20 17:12:34

标签: sql sql-server-2005

我正在尝试创建一个简单的视图,从2个数据库中获取数据。

我有一张booking表,只显示每次预订一次,还有一张日记表,是每次预订的备注。

每个预订在日记表中多次显示,但我只想在我的视图中查看最新的笔记和预订信息

由于某些原因,这不起作用

SELECT     
    t0.BOOKNO, t0.PARTY, t0.TOUR, t0.DEPART, t0.DEP7, t0.BOOK7, t0.PAID, t0.APRICE, t1.TEXT
FROM         
    (SELECT DISTINCT 
        TOP (100) PERCENT 
        dbo.DIARY.ADDED, dbo.BOOKINGS.BOOKNO, dbo.BOOKINGS.PARTY, 
        dbo.BOOKINGS.TOUR, dbo.BOOKINGS.DEPART, 
        dbo.BOOKINGS.DEP7, dbo.BOOKINGS.BOOKED, dbo.BOOKINGS.BOOK7, dbo.BOOKINGS.PAID, 
        dbo.BOOKINGS.APRICE, dbo.BOOKINGS.STATUS
     FROM          
        dbo.BOOKINGS 
     CROSS JOIN
        dbo.DIARY
     WHERE      
        (dbo.BOOKINGS.PAID IS NULL) 
        OR (dbo.BOOKINGS.PAID = 0)
     GROUP BY 
        dbo.BOOKINGS.BOOKNO, dbo.BOOKINGS.PARTY, dbo.BOOKINGS.TOUR, dbo.BOOKINGS.DEPART, 
        dbo.BOOKINGS.DEP7, dbo.BOOKINGS.BOOKED, dbo.BOOKINGS.APRICE, dbo.BOOKINGS.STATUS, 
        dbo.BOOKINGS.BOOK7, dbo.BOOKINGS.PAID, dbo.DIARY.ADDED
     HAVING      
        (dbo.BOOKINGS.STATUS <> 'xl') AND 
        (dbo.BOOKINGS.DEPART > CONVERT(int, GETDATE()))
     ORDER BY 
        dbo.BOOKINGS.BOOKNO) AS t0 
INNER JOIN
   (SELECT     
       BOOKNO, TEXT, MAX(ADDED) AS added
    FROM          
       dbo.DIARY AS DIARY_1
    GROUP BY BOOKNO, TEXT) AS t1 ON t0.BOOKNO = t1.BOOKNO

我试过这个,但它无法解析查询文本?

;WITH MostRecentBookings AS (  SELECT     dbo.DIARY.ADDED7, dbo.DIARY.ADDED, dbo.BOOKINGS.BOOKNO, dbo.BOOKINGS.PARTY, dbo.BOOKINGS.TOUR, dbo.BOOKINGS.DEPART, 
                      dbo.BOOKINGS.DEP7, dbo.BOOKINGS.BOOKED, dbo.BOOKINGS.BOOK7, dbo.BOOKINGS.PAID, dbo.BOOKINGS.APRICE, dbo.BOOKINGS.STATUS, 
                      dbo.DIARY.TEXT, ROW_NUMBER() OVER(PARTITION BY dbo.BOOKINGS.BOOKNO ORDER BY dbo.DIARY.ADDED DESC) AS 'RowNum'  
FROM         dbo.BOOKINGS INNER JOIN   dbo.DIARY ON dbo.BOOKINGS.BOOKNO = dbo.DIARY.BOOKNO 
WHERE     (dbo.BOOKINGS.PAID IS NULL) OR     (dbo.BOOKINGS.PAID = 0)) 
SELECT    *  FROM    MostRecentBookings 
WHERE    RowNum = 1 

1 个答案:

答案 0 :(得分:0)

基本上,您可以使用CTE(公用表表达式)与ROW_NUMBER()函数结合来实现此目的。类似的东西:

;WITH MostRecentBookings AS
(
   SELECT 
      (some columns),
      ROW_NUMBER() OVER(PARTITION BY b.BOOK_NO ORDER BY d.ADDED DESC) AS 'RowNum'
   FROM
      dbo.Booking b
   INNER JOIN
      dbo.Diary d ON ..........
)
SELECT
   (some columns)
FROM
   MostRecentBookings
WHERE
   RowNum = 1

基本上,CTE会在两个表之间进行连接,然后它会将您的数据“分区”BOOK_NO - 这样,每个唯一的预订都会得到一个从1开始的行号。

编号是这样的,即最近的条目获得数字1,而前一个条目获得后续更高的数字。从该CTE中,选择RowNum = 1的条目作为最近预订的列表。