查询以查找为文件插入的最近日期的记录数

Query to find count of records inserted for a file for the latest date

我正在尝试创建一个 SQL 查询以获取每天最新日期的记录数。

我有 4 列数据 table:

File_Name, Insert_TimeStamp, MobileNumber, Message_Id (unique)

假设为 Insert_TimeStamp 13/12/2021 插入了一个包含 100 条记录的文件,File_Name 对于日期 XYZ_1312021 的所有记录都是相同的。 Like wise 日常文件将被插入。

我只是想在 SQL 的帮助下通过查看此数据 table 每天创造 1 条新记录。结果就像

TotalNumberRecords,File_Name,Insert_TimeStamp(最新日期),状态(已收到)。

但是我遇到了一个错误

Error saving the query field. Invalid column name 'Total_Record_Received'

我创建的

SQL:

    Select Top 1
file_name,
INSERT_TIMESTAMP,
Total_Record_Received,
'Received' as Status
from
(
Select 
file_name,
INSERT_TIMESTAMP,
Count(*) as Total_Record_Received,
ROW_NUMBER() OVER(PARTITION by file_name ORDER BY INSERT_TIMESTAMP ASC ) as rn
from [Master-SMS MessageALL] a
Group by file_name, INSERT_TIMESTAMP) t
Where t.rn = 1

示例数据:

File_Name     Insert_TimeStamp   Mobile_Number  MessageID
xyz_13122021   13/12/2021         7814154        mm_001
xyz_13122021   13/12/2021         7516546        mm_002
xyz_13122021   13/12/2021         1541646        mm_003
xyz_13122021   13/12/2021         5446561        mm_004
xyz_13122021   13/12/2021         5456456        mm_005
xyz_13122021   13/12/2021         8749849        mm_006
xyz_12122021   12/12/2021         7814154        mm_007
xyz_12122021   12/12/2021         8749849        mm_008
xyz_11122021   11/12/2021         8749848        mm_009

结果:

File_Name     TotalRecords     Insert_TimeStamp   Status
xyz_13122021      6               13/12/2021      Received

您需要的是一个简单的 GROUP BY 查询

SELECT File_Name,
       COUNT(*) AS TotalRecords,
       Insert_TimeStamp,
       'Received' AS Status
FROM   [Master-SMS MessageALL]
WHERE  Insert_TimeStamp = (SELECT MAX(Insert_TimeStamp) FROM [Master-SMS MessageALL])
GROUP BY File_Name, Insert_TimeStamp

或者您可以使用 TOP 1 行顺序 Insert_TimeStamp 降序

SELECT TOP 1
       File_Name,
       COUNT(*) AS TotalRecords,
       Insert_TimeStamp,
       'Received' AS Status
FROM   [Master-SMS MessageALL]
GROUP BY File_Name, Insert_TimeStamp
ORDER BY Insert_TimeStamp DESC

或者如果您想使用 row_number()

SELECT *
FROM
(
    SELECT File_Name,
           COUNT(*) AS TotalRecords,
           Insert_TimeStamp,
           'Received' AS Status,
           RN = ROW_NUMBER() OVER (ORDER BY Insert_TimeStamp DESC)
    FROM   [Master-SMS MessageALL]
    GROUP BY File_Name, Insert_TimeStamp
) AS D
WHERE D.RN = 1