获取基于最新日期的最新数据 - MSSQL

时间:2016-11-22 13:15:35

标签: sql sql-server select

这就是我的表在数据库中的显示方式: 我有2张桌子:

 1. Location = ID, Name
 2. Product = ProdID, LocationID, CreatedDate

-------------------------------------------------
| ID           | Location     | CreatedDate     
-------------------------------------------------
| 1234         | Location 1   | 2016-11-17 12:39
| 4567         | Location 1   | 2016-11-17 12:39 
| 8978         | Location 1   | 2016-11-17 12:39       
| 8978         | Location 2   | 2016-11-17 13:39
| 2578         | Location 1   | 2016-11-17 12:39
| 1234         | Location 2   | 2016-11-18 12:39
-------------------------------------------------

我想检索如下表格:

----------------------------------------------
| Location 1   | Location 2   | Location 3   |
----------------------------------------------
| 1234         | 1234         |              |
| 4567         |              |              |
| 8978         | 8978         | 8978         |
| 2578         | 2578         | 2578         |
----------------------------------------------

另外,对于上表,我想要一个查询来获取每个位置上最后扫描的唯一项目的总金额:

Location 1 count = 1
Location 2 count = 1
Location 3 count = 2

解释:上表显示了我们仓库中不同项目的列表。 基本上,如果项目1234在位置1在12:00扫描,之后在13:00扫描到位置2,则查询必须仅从位置2获取数据,因为它是基于日期的最后更新。

2 个答案:

答案 0 :(得分:1)

您可以尝试以下查询

对于要求1

select 
    case when Location1 = 0 then null else Location1 end Location1,
    case when Location2 = 0 then null else Location2 end Location2,
    case when Location3 = 0 then null else Location3 end Location3
from(
    SELECT 
        SUM(case when location_id = 'Location 1' then id else 0 end) Location1, 
        SUM(case when location_id = 'Location 2' then id else 0 end) Location2, 
        SUM(case when location_id = 'Location 3' then id else 0 end) Location3
    from Product
    group by ProdID) t1;

以下是上述查询的结果

enter image description here

对于要求2,

select 
     sum(case when Location2 = 0 then 1 else 0 end) Location1,
     sum(case when Location3 = 0 and Location2 <> 0 then 1 else 0 end) Location2,
     sum(case when Location3 = 0 then 0 else 1 end) Location3
from(
    SELECT 
         SUM(case when location_id = 'Location 1' then id else 0 end) Location1, 
         SUM(case when location_id = 'Location 2' then id else 0 end) Location2, 
         SUM(case when location_id = 'Location 3' then id else 0 end) Location3
    from Product
    group by id) t1;

以下是上述查询的结果

enter image description here

注意:仅当ProdID为整数时,上述查询才有效。

希望这可以帮助你。

答案 1 :(得分:0)

显然,您将在ID = LocationID上进行内连接。

除此之外,这是关于你的'where'条款。您需要获得每个项目的最大(日期)的子查询,我猜测这是您缺少的部分。