3

我有一个查询,它从具有第 1 列重复记录的表中返回数据,尽管其他列中可能有不同的值。我只想将第 1 列中的每个值的一条记录带入使用标准选择正确记录的视图中。

这是查询;

SELECT 
   PrimaryColumn1,
   Column2,
   Column3,
   Date1,
   Date2
FROM
   My_Table

我希望在PrimaryColumn1我创建的基于最新日期的视图中只有不同的值Date1,如果这也是重复的,则在 Date2 中。

我尝试执行以下操作,但无法使其工作

SELECT 
   PrimaryColumn1,
   Column2,
   Column3,
   Date1,
   Date2
FROM    
   (SELECT  
        [PrimaryColumn1,
        Column2,
        Column3,
        Date1,
        Date2,
        ROW_NUMBER() OVER(PARTITION BY [Date1] ORDER BY Date2) AS RowNumber
    FROM    
        My_Table)
WHERE   
    RowNumber = 1

任何帮助将不胜感激。

在下面的建议之后,最终的查询看起来像这样:

SELECT 
    PrimaryColumn1,
    Column2, 
    Column3,
    Date1,
    Date2
FROM    
    (SELECT  
         [PrimaryColumn1,
         Column2,
         Column3,
         Date1,
         Date2,
         ROW_NUMBER() OVER(PARTITION BY PrimaryColumn1
                           ORDER BY Date1 DESC, Date2 DESC) AS RowNumber) data
WHERE 
    RowNumber = 1
4

3 回答 3

1

我认为你的ROW_NUMBER()陈述应该是这样的:

ROW_NUMBER() OVER(PARTITION BY PrimaryColumn1
                      ORDER BY Date1 DESC, Date2 DESC) AS RowNumber

Since you're looking for the most recent record for each PrimaryColumn1 value, this should do what you want (as I understand it).

于 2012-12-07T23:02:52.440 回答
1

CROSS APPLY is a great way to do something like this. For example, this pulls a record for each CategoryID in the Products table and shows the product data for the most expensive product in each category.

This effectively gives you a way to use a correlated subquery in a join. Pretty cool.

USE Northwind;
GO
--Get a distinct list of CategoryID values
--From the dbo.Products table, and show the
--Product details for the most expensive product
--in each of those categories....
SELECT DISTINCT 
  Prod.CategoryID,
  TopProd.ProductID,
  TopProd.ProductName,
  TopProd.UnitPrice
FROM dbo.Products AS Prod
CROSS APPLY 
(
  --Find the top 1 product in each category by unitprice
  SELECT TOP 1 
    ProductID,
    ProductName,
    UnitPrice
  FROM dbo.Products
  --This is the "correlated" part where 
  --we filter by the outer queries' CategoryID
  WHERE CategoryID = Prod.CategoryID
  --The ORDER BY determines which product
  --you see for each category.  In this
  --case I'll get the most expensive product
  ORDER BY UnitPrice DESC
) AS TopProd;
于 2012-12-07T23:19:08.907 回答
0
SELECT 
   PrimaryColumn1,
   Column2,
   Column3,
   Date1,
   Date2
FROM My_Table
INNER JOIN  
   (SELECT  PrimaryColumn1,
        MAX(Date1) AS max_Date1,
        MAX(Date2) AS max_Date2,
        FROM My_Table
        GROUP BY PrimaryColumn1
    ) AS Maxes
ON Maxes.PrimaryColumn1 = My_Table.PrimaryColumn1
AND Maxes.max_Date1 = My_Table.Date1
AND Maxes.max_Date2 = My_Table.Date2
于 2012-12-07T23:07:29.013 回答