我有一个表格,其中包含MS SQL 2005表格中许多不同"事物"的价格.每件事每天有数百条记录,不同的东西在不同的时间获得价格更新.
ID uniqueidentifier not null,
ThingID int NOT NULL,
PriceDateTime datetime NOT NULL,
Price decimal(18,4) NOT NULL
Run Code Online (Sandbox Code Playgroud)
我需要获得今天最新的一组价格.下面的查询有效但我收到了数百行,我必须循环它们,并且每个ThingID只提取最新的一行.我怎样才能(例如通过GROUP BY)说我想要每个ThingID最新的一个?或者我必须使用子查询?
SELECT *
FROM Thing
WHERE ThingID IN (1,2,3,4,5,6)
AND PriceDate > cast( convert(varchar(20), getdate(), 106) as DateTime)
Run Code Online (Sandbox Code Playgroud)
更新:为了隐藏复杂性,我将ID列放在一个int中.在现实生活中它是GUID(而不是顺序类).我已经更新了上面的表def以使用uniqueidentifier.
更新:请参阅下文
我有桌子:数据
+-----------------------+--------------+-----------+
| State | d_country | d_postcode|
+-----------------------+--------------+-----------+
| State1 | Country1 | 1111 |
| State2 | Country2 | 2222 |
| State3 | Country3 | 3333 |
| State4 | Country4 | 4444 |
+-----------------------+--------------+-----------+
Run Code Online (Sandbox Code Playgroud)
另一个表:用户
+-----------------------+--------------+-----------+
| Name | u_country | u_postcode|
+-----------------------+--------------+-----------+
| Name1 | Country3 | 3333 |
| Name2 | Country5 | 5555 |
| Name3 | | 6666 |
| Name4 | Country6 | 6666 |
| Name5 | Country6 | …Run Code Online (Sandbox Code Playgroud)