不同情况下的订购代码

时间:2019-06-19 19:45:11

标签: sql sql-server tsql sql-server-2012

我正在尝试完成以下任务。在此,我正在谈论一小段数据。我们有一个可以在不同日期使用不同代码的人。

DECLARE @t TABLE (PersonId INT, CDate DATE, Code VARCHAR(20))
INSERT INTO @t VALUES 
(2345,'20161010','V1'),(2345,'20170104','V2'),(2345,'20170320','V3'),(2345,'20170612','V4'),
(2421,'20161005','UNS'),(2421,'20161102','V1'),(2421,'20170118','V2'),(2421,'20170418','V3'),
(2421,'20170712','V4'),(2421,'20171004','V5'),(2421,'20171220','V6'),(2421,'20180113','LFM'),
(2421,'20180321','V7'),(2421,'20180822','V8'),(2421,'20190220','V9'),(2421,'20190315','EOT'),
(2430,'20161020','V1'),(2430,'20170116','V2'),(2430,'20170413','V3'),(2430,'20170726','EOT'),
(3004,'20161110','V1'),(3004,'20170131','V2'),(3004,'20170425','V3'),(3004,'20170503','LFM'),
(3004,'20170512','LFM'),(3004,'20170718','V4'),(3004,'20170725','LFM'),(3004,'20171010','V5'),
(3004,'20180102','V6'),(3004,'20180108','LFM'),(3004,'20180115','LFM'),(3004,'20180125','UNS'),
(3004,'20180328','V7'),(3004,'20180406','LFM'),(3004,'20180911','V8'),(3004,'20190227','V9'),
(3004,'20190306','LFM'),(3004,'20190313','UNS'),
(31740,'20190514','V1')

我们要寻找的结果如下。我已在右侧添加了PersonId作为额外信息,以便您可以查看应计入哪些。最终结果中的代码应按CDate的顺序排列在所有不同人员上。代码EOT应该是最后一个。

RowNr   Code    Total   |
========================|
1       UNS     1       |   2421
2       V1      5       |   2345,2421,2430,3004,31740
3       V2      4       |   2345,2421,2430,3004
4       V3      4       |   2345,2421,2430,3004
5       LFM     1       |   3004
6       LFM     1       |   3004
7       V4      3       |   2345,2421,3004
8       LFM     1       |   3004 
9       V5      2       |   2421,3004
10      V6      2       |   2421,3004
11      LFM     2       |   2421,3004
12      LFM     1       |   3004
13      UNS     1       |   3004
14      V7      2       |   2421,3004
15      LFM     1       |   3004
16      V8      2       |   2421,3004
17      V9      2       |   2421,3004
18      LFM     1       |   3004
19      UNS     1       |   3004
20      EOT     2       |   2421,2430

谁能提供一个起点或帮助我们实现这一目标?

1 个答案:

答案 0 :(得分:1)

对于版本2012,您可以在function foobar<T extends "foo" | "bar">(func: (arg: T) => void): (arg: "foo" | "bar") => void { return func; } 函数中使用T结构

xml path

Demo

,但请注意样本数据和所需结果不兼容。