我有这个查询,其中包含case
语句:
SELECT
tsp_filtered_data.increment_id,
tsp_filtered_data.ESN,
tsp_filtered_data.Model,
tsp_filtered_data.Fault,
CASE
WHEN tsp_filtered_data.ESN RLIKE '^[0-9A-F]{8}$'
THEN 'valid ESN'
ELSE 'Invalid ESN'
END AS ESN_status
FROM
tsc_document_status
INNER JOIN
tsp_filtered_data ON tsp_filtered_data.Document_id = tsc_document_status.warehouse_transfer_note_id
ORDER BY
tsp_filtered_data.ESN DESC
并返回此输出:
我可以使用有效ESN'的结果吗?和'无效的ESN'
按顺序排列我的要求是放置所有无效的ESN'列出查询结果的顶部,然后是有效的ESN'名单。
如何修改查询..
答案 0 :(得分:3)
使用ORDER BY FIELD
:
ORDER BY FIELD(ESN_status, 'Invalid ESN', 'Valid ESN')
完整查询:
SELECT
t2.increment_id,
t2.ESN,
t2.Model,
t2.Fault,
CASE WHEN t1.ESN RLIKE '^[0-9A-F]{8}$'
THEN 'Valid ESN' ELSE 'Invalid ESN' END AS ESN_status
FROM tsc_document_status t1
INNER JOIN tsp_filtered_data t2
ON t1.Document_id = t2.warehouse_transfer_note_id
ORDER BY
ORDER BY FIELD(ESN_status, 'Invalid ESN', 'Valid ESN')
请注意,我引入了表别名,使您的查询更容易阅读(IMO)。您可以自由地为ORDER BY
子句添加更多级别的排序,但我的答案应该解决您在问题中提出的要求。
答案 1 :(得分:0)
From this: 8******5
To: 888888**
首先,它会按照SELECT
tsp_filtered_data.increment_id,
tsp_filtered_data.ESN,
tsp_filtered_data.Model,
tsp_filtered_data.Fault,
case when tsp_filtered_data.ESN RLIKE '^[0-9A-F]{8}$' then 'valid ESN' else 'Invalid ESN' end AS ESN_status
FROM
tsc_document_status
INNER JOIN tsp_filtered_data ON tsp_filtered_data.Document_id = tsc_document_status.warehouse_transfer_note_id
ORDER BY ESN_status,tsp_filtered_data.ESN DESC //Modified line
的升序对整个结果集进行排序。现在,对于具有相同ESN_status
的记录,它将按ESN_status
希望它有所帮助!