我在一个表中有几行,如下所示:
[id], [date1], [action1], [date2], [action2], [date3], [action3], [date4], [action4]
并且每行想要返回操作(由单个字母定义)与所需代码匹配的最新日期。
我怀疑我需要在某处使用MAX()函数,但不知道如何启动?
答案 0 :(得分:0)
试试这个,
(您可以设置日期列而不是我的变量。)
DECLARE @Date1 AS DATE
DECLARE @Date2 AS DATE
DECLARE @Date3 AS Date
SET @Date1 = GETDATE()
SET @Date2 = GETDATE() + 4
SET @Date3 = GETDATE() -4
SELECT
CASE
WHEN
(CASE WHEN @Date1 > @Date2 THEN @Date1 ELSE @Date2 END) > @Date3 THEN
(CASE WHEN @Date1 > @Date2 THEN @Date1 ELSE @Date2 END) ELSE @Date3 END AS result
答案 1 :(得分:0)
您可以将UNPIVOT
与公用表格表达式结合使用。让我们假设你的表是这样的:
CREATE TABLE MyTable
(
ID int NOT NULL IDENTITY PRIMARY KEY,
Date1 date NOT NULL,
Action1 char(1) NOT NULL,
Date2 date NOT NULL,
Action2 char(1) NOT NULL,
Date3 date NOT NULL,
Action3 char(1) NOT NULL,
Date4 date NOT NULL,
Action4 char(1) NOT NULL
);
以及一些示例数据:
INSERT INTO MyTable(Date1, Action1, Date2, Action2, Date3, Action3, Date4, Action4)
VALUES
('20170101', 'A', '20170201', 'A', '20170201', 'B', '20170101', 'C'),
('20170103', 'A', '20170203', 'B', '20170205', 'A', '20170101', 'C');
然后您可以UNPIVOT
进行操作,然后查看日期,然后加入这些不透明的结果,如下所示:
WITH Actions AS
(
SELECT ID, [Action]
FROM
(
SELECT ID, Action1, Action2, Action3, Action4
FROM MyTable
) P
UNPIVOT
(
[Action] FOR Col IN([Action1], [Action2], [Action3], [Action4])
) U
),
Dates AS
(
SELECT ID, [Date]
FROM
(
SELECT ID, Date1, Date2, Date3, Date4
FROM MyTable
) P
UNPIVOT
(
[Date] FOR Col IN([Date1], [Date2], [Date3], [Date4])
) U
)
SELECT
A.ID, MAX(D.[Date]) AS MaxDate
FROM
Actions A
INNER JOIN Dates D ON D.ID = A.ID
WHERE
A.Action = 'A'
GROUP BY
A.ID;
结果是
ID MaxDate
----------- ----------
1 2017-02-01
2 2017-02-05