根据MAX DATE得到所有列的不同结果

时间:2015-09-27 15:34:41

标签: sql sql-server max

使用SQL Server 2012

我已经看过关于这个主题的一些主题,但我找不到涉及查询中多个连接的主题。我无法在此数据库上创建VIEW,因此需要连接。

查询

SELECT 

      p.Price
      ,s.Type
      ,s.Symbol
      , MAX(d.Date) Maxed
  FROM AdventDW.dbo.FactPrices p
  INNER JOIN dbo.DimSecurityMaster s
  ON s.SecurityID = p.SecurityID
  INNER JOIN dbo.DimDateTime d
   ON
  p.DateTimeKey = d.DateTimeKey
  GROUP BY p.Price ,
           s.Type ,
           s.Symbol
ORDER BY s.Symbol

查询有效,但不会产生明显的结果。我使用Order by来验证结果,但是一旦我开始工作就不需要它。我的结果集看起来像这样。

Price   Type    Symbol  Maxed
10.57   bfus    *bbkd           3/31/1989
10.77   bfus    *bbkd           2/28/1990
100.74049   cbus    001397AA6       8/2/2005
100.8161    cbus    001397AA6       7/21/2005

我想要的结果集是

Price   Type    Symbol  Maxed
10.77   bfus    *bbkd           2/28/1990
100.74049   cbus    001397AA6       8/2/2005

以下是我尝试过的一些其他StackOverflow线程但无法使用我的特定查询

How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?

SQL Selecting distinct rows from multiple columns based on max value in one column

3 个答案:

答案 0 :(得分:3)

如果您想要最长日期的数据,请使用row_number()而不是group by

SELECT ts.*
FROM (SELECT p.Price, s.Type, s.Symbol, d.Date,
             ROW_NUMBER() OVER (PARTITION BY s.Type, s.Symbol
                                ORDER BY d.Date DESC
                               ) as seqnum
      FROM AdventDW.dbo.FactPrices p INNER JOIN
           dbo.DimSecurityMaster s
           ON s.SecurityID = p.SecurityID INNER JOIN
           dbo.DimDateTime d
           ON p.DateTimeKey = d.DateTimeKey
     ) ts
WHERE seqnum = 1
ORDER BY s.Symbol;

答案 1 :(得分:1)

您应该使用派生表,因为您实际上只想将DateTimeKey表分组以获得MAX日期。

SELECT p.Price ,
       s.Type ,
       s.Symbol ,
       tmp.MaxDate
FROM AdventDW.dbo.FactPrices p
INNER JOIN dbo.DimSecurityMaster s ON s.SecurityID = p.SecurityID
INNER JOIN
  ( SELECT MAX(d.Date) AS MaxDate ,
           d.DateTimeKey
   FROM dbo.DimDateTime d
   GROUP BY d.DateTimeKey ) tmp ON p.DateTimeKey = tmp.DateTimeKey
ORDER BY s.Symbol;

答案 2 :(得分:1)

    /* 
    this is your initial select which is fine because this is base from your original criteria, 
I cannot ignore this so i'll keep this in-tact. Instead from here i'll create a temp
    */

  SELECT 
      p.Price
      , s.Type
      , s.Symbol
      , MAX(d.Date) Maxed
  INTO #tmpT
  FROM AdventDW.dbo.FactPrices p
  INNER JOIN dbo.DimSecurityMaster s
      ON s.SecurityID = p.SecurityID
  INNER JOIN dbo.DimDateTime d
      ON p.DateTimeKey = d.DateTimeKey
  GROUP BY p.Price ,
       s.Type ,
       s.Symbol
  ORDER BY s.Symbol

SELECT innerTable.Price, innerTable.Symbol, innerTable.Type, innerTable.Maxed 
FROM (

   SELECT
      ROW_NUMBER () OVER (PARTITION BY t1.Symbol, t1.Type, t1.Maxed ORDER BY t1.Maxed DESC) as row 
      , *
   FROM #tmpT AS t1
) AS innerTable
WHERE row = 1

DROP TABLE #tmpT