假设我有一个包含以下列的表:
Id, ConnectionId, File, FileCreated
int, int, varchar, DateTime
数据示例
此外,假设它填充了未分类的数据,如下所示:
1, 3, "a.dat", 2018-05-16 13:53:40.008
2, 1, "b.dat", 2018-05-16 13:53:40.007
3, 3, "c.dat", 2018-05-16 13:53:40.009
4, 3, "z.dat", 2018-05-16 13:53:40.002
5, 3, "h.dat", 2018-05-16 13:53:40.003
6, 2, "ba.dat", 2018-05-16 13:53:40.004
7, 3, "zy.dat", 2018-05-16 13:53:40.005
8, 1, "f.dat", 2018-05-16 13:53:40.001
9, 1, "cd.dat", 2018-05-16 13:53:40.006
我如何查询此数据以便数据集返回我:
预期结果
我正在寻找的结果如下:
(注意:我将这些放入群组中,以便您可以看到它们首先根据ConnectionId返回(可能是分组)。
8, 1, "f.dat", 2018-05-16 13:53:40.001
4, 3, "z.dat", 2018-05-16 13:53:40.002
6, 2, "ba.dat", 2018-05-16 13:53:40.004
5, 3, "h.dat", 2018-05-16 13:53:40.003
9, 1, "cd.dat", 2018-05-16 13:53:40.006
7, 3, "zy.dat", 2018-05-16 13:53:40.005
2, 1, "b.dat", 2018-05-16 13:53:40.007
1, 3, "a.dat", 2018-05-16 13:53:40.008
3, 3, "c.dat", 2018-05-16 13:53:40.009
希望我的示例向您展示这些不是严格基于时间的,也不是严格基于connectionId的。这两者都是。
答案 0 :(得分:3)
您可以在SELECT
ENAME,
CONVERT(VARCHAR(3),DATEDIFF(MONTH, DOJ, GETDATE())/12) +' years '+
CONVERT(VARCHAR(2),DATEDIFF(MONTH, DOJ, GETDATE()) % 12)+ ' months'
AS AgeInYears,
CONVERT(VARCHAR(3),DATEDIFF(MONTH, hiredate, GETDATE())/12) +' years '+
CONVERT(VARCHAR(2),DATEDIFF(MONTH, hiredate, GETDATE()) % 12)+ ' months'
AS EXPERIENCEInYears
FROM EMPLOYEE;
子句中使用row_number()
:
order by
答案 1 :(得分:3)
尝试这样
DECLARE @mockup TABLE(Id INT,ConnectionId INT,[File] VARCHAR(100),FileCreated DATETIME2);
INSERT INTO @mockup VALUES
(1, 3, 'a.dat','2018-05-16T13:53:40.008')
,(2, 1, 'b.dat','2018-05-16T13:53:40.007')
,(3, 3, 'c.dat','2018-05-16T13:53:40.009')
,(4, 3, 'z.dat','2018-05-16T13:53:40.002')
,(5, 3, 'h.dat','2018-05-16T13:53:40.003')
,(6, 2, 'ba.dat','2018-05-16T13:53:40.004')
,(7, 3, 'zy.dat','2018-05-16T13:53:40.005')
,(8, 1, 'f.dat','2018-05-16T13:53:40.001')
,(9, 1, 'cd.dat','2018-05-16T13:53:40.006');
SELECT *
FROM @mockup
ORDER BY ROW_NUMBER() OVER(PARTITION BY ConnectionId ORDER BY FileCreated)
,FileCreated;
编辑这个很棒的答案来添加结果(并将更新的DateTime添加到DateTime2): 太棒了 - 结果完全符合我的预期结果。
Id ConnectionId File FileCreated
8 1 f.dat 2018-05-16 13:53:40.0010000
4 3 z.dat 2018-05-16 13:53:40.0020000
6 2 ba.dat 2018-05-16 13:53:40.0040000
5 3 h.dat 2018-05-16 13:53:40.0030000
9 1 cd.dat 2018-05-16 13:53:40.0060000
7 3 zy.dat 2018-05-16 13:53:40.0050000
2 1 b.dat 2018-05-16 13:53:40.0070000
1 3 a.dat 2018-05-16 13:53:40.0080000
3 3 c.dat 2018-05-16 13:53:40.0090000