从最大日期中选择全部

时间:2014-10-31 10:54:41

标签: sql sql-server tsql

早上好,

我正在为最新的金属价格编写SQL查询,并将最新日期放入数据库。下面的示例表:

ID    Date Created
1     01/01/01 01:01
2     01/01/01 01:02
3     01/01/01 01:03
4     01/01/01 01:04
1     02/01/01 01:01
2     02/01/01 01:02

因此,我希望得到以下结果:

ID    Date Created
1     02/01/01 01:01
2     02/01/01 01:02

当我运行以下查询时,它只是给我输入日期库的最后一个,所以从上面的例子中它将是ID 2 DateCreated 02/01/01 01:02。我正在使用的查询如下:

SELECT mp.MetalSourceID, ROUND(mp.PriceInPounds,2), 
mp.UnitPrice, mp.HighUnitPrice, mp.PreviousUnitPrice, 
mp.PreviousHighUnitPrice, ms.MetalSourceName, 
ms.UnitBasis, cu.Currency 
FROM tblMetalPrice  AS mp
INNER JOIN tblMetalSource AS ms
ON tblMetalPrice.MetalSourceID = tblMetalSource.MetalSourceID 
INNER JOIN tblCurrency AS cu
ON tblMetalSource.CurrencyID = tblCurrency.CurrencyID  
WHERE DateCreated = (SELECT MAX (DateCreated) FROM tblMetalPrice)
GROUP BY mp.MetalSourceID;

任何人都可以帮助它让我疯狂不知道,我的大脑在星期五早上死了。

由于

3 个答案:

答案 0 :(得分:1)

where子句使用相关子查询:

WHERE DateCreated = (SELECT MAX(DateCreated) FROM tblMetalPrice mp2 WHERE mp2.id = mp.id)

答案 1 :(得分:0)

你可以加入一个子查询,我不认为你需要这个组,或者确实是where子句(因为这是由联接处理的)。

SELECT mp.MetalSourceID, 
       ROUND(mp.PriceInPounds,2), 
       mp.UnitPrice, 
       mp.HighUnitPrice, 
       mp.PreviousUnitPrice, 
       mp.PreviousHighUnitPrice, 
       ms.MetalSourceName, 
       ms.UnitBasis, 
       cu.Currency 
FROM tblMetalPrice  AS mp
INNER JOIN tblMetalSource AS ms
    ON tblMetalPrice.MetalSourceID = tblMetalSource.MetalSourceID 
INNER JOIN tblCurrency AS cu
    ON tblMetalSource.CurrencyID = tblCurrency.CurrencyID  
INNER JOIN (SELECT ID,MAX(DateCreated) AS maxdate FROM tblMetalPrice GROUP BY ID) AS md
    ON md.ID = mp.ID 
    AND md.maxdate = mp.DateCreated

答案 2 :(得分:0)

with maxDates as (select max(datecreated) maxd, ids grp , count(1) members from s_tableA group by ids having count(1) > 1) select ids, datecreated from s_tableA,maxDates where maxd = datecreated and ids = grp;

此查询将提供您想要的结果。相关的子查询往往会消耗大量的处理时间,因为对于外部查询的每一行,它必须处理内部查询中的所有行。