【发布时间】:2020-04-10 18:05:58
【问题描述】:
我有一个包含 ID, Workitem_Type, [STATUS], Workitem, CompletedDate, WORK, Log_createdDate 列的表 TestTable
数据如下:
+----+---------------+--------+-----------+-------------------------+-------+-------------------------+
| ID | Workitem_Type | STATUS | Workitem | CompletedDate | WORK | Log_createdDate |
+----+---------------+--------+-----------+-------------------------+-------+-------------------------+
| 1 | Remainder | Pass | Workitem1 | 2019-12-19 01:20:35.060 | Work1 | 2014-12-17 00:36:38.557 |
| 2 | Remainder | Pass | Workitem2 | 2019-12-19 01:20:35.060 | Work2 | 2015-12-17 00:36:38.557 |
| 3 | Remainder | Pass | Workitem3 | 2019-12-17 01:20:35.060 | Work3 | 2018-12-17 00:36:38.557 |
| 4 | Request | Pass | Workitem4 | 2019-12-18 01:20:35.060 | Work4 | 2017-12-17 00:36:38.557 |
| 5 | Remainder | Pass | Workitem5 | 2019-12-17 01:20:35.060 | Work5 | 2016-12-17 00:36:38.557 |
+----+---------------+--------+-----------+-------------------------+-------+-------------------------+
我必须根据Workitem_Type、CompletedDate 给予优先级,并且应该在单个查询中按相同的优先级和Log_createdDate 排序。所以输出应该如下所示:
+----+---------------+--------+-----------+-------------------------+-------+-------------------------+
| ID | Workitem_Type | STATUS | Workitem | CompletedDate | WORK | Log_createdDate |
+----+---------------+--------+-----------+-------------------------+-------+-------------------------+
| 1 | Remainder | Pass | Workitem1 | 2019-12-19 01:31:12.620 | Work1 | 2014-12-17 00:36:38.557 |
| 2 | Remainder | Pass | Workitem2 | 2019-12-19 01:31:12.637 | Work2 | 2015-12-17 00:36:38.557 |
| 5 | Remainder | Pass | Workitem5 | 2019-12-17 01:31:12.637 | Work5 | 2016-12-17 00:36:38.557 |
| 3 | Remainder | Pass | Workitem3 | 2019-12-17 01:31:12.637 | Work3 | 2018-12-17 00:36:38.557 |
| 4 | Request | Pass | Workitem4 | 2019-12-18 01:31:12.637 | Work4 | 2017-12-17 00:36:38.557 |
+----+---------------+--------+-----------+-------------------------+-------+-------------------------+
我尝试了以下查询:
SELECT *, CASE WHEN Workitem_Type = 'Remainder' THEN
CASE WHEN CompletedDate > GETDATE() THEN 1 ELSE 2 END
ELSE 3 END AS [Priority]
FROM TestTable
ORDER BY [Priority], Log_createdDate;
但我不希望Priority 列出现在我的输出中。那么在单个查询中是否可以在没有优先级列的情况下获得上述输出?
请找到db<>fiddle 。
【问题讨论】:
-
然后不要把它(
Priority)放在你的SELECT中,把表达式放在你的ORDER BY中。 -
@Larnu 但我需要基于优先级列的排序
-
是的,所以只在
ORDER BY中表达。您订购的内容不必包含在SELECT中(对此有一些警告,但在此查询中没有)。 -
@Larnu 是的,根据sticky bit 的回答,使用
ORDER BY中的CASE WHEN表达式解决了我的问题。也感谢您的评论。
标签: sql sql-server select sql-order-by sql-server-2017