[英]How to do this query in T-SQL
I have table with 3 columns AB C. 我有3列AB C的表。
I want to select * from this table, but ordered by a specific ordering of column A. 我想从这个表中选择*,但是按照A列的特定顺序排序。
In other words, lets' say column A contains "stack", "over", "flow". 换句话说,让我们说A列包含“stack”,“over”,“flow”。
I want to select * from this table, and order by column A in this specific ordering: "stack", "flow", "over" - which is neither ascending nor descending. 我想从这个表中选择*,并按照这个特定的顺序按列A排序:“stack”,“flow”,“over” - 既不是升序也不是降序。
Is it possible? 可能吗?
You can use a CASE statement in the ORDER BY clause. 您可以在ORDER BY子句中使用CASE语句。 For example ... 例如 ...
SELECT *
FROM Table
ORDER BY
CASE A
WHEN 'stack' THEN 1
WHEN 'over' THEN 2
WHEN 'flow' THEN 3
ELSE NULL
END
Check out Defining a Custom Sort Order for more details. 查看定义自定义排序顺序以获取更多详细信息。
A couple of solutions: 几个解决方案:
Create another table with your sort order, join on Column A to the new table (which would be something like TERM as STRING, SORTORDER as INT). 使用排序顺序创建另一个表,将A列连接到新表(这将类似于TERM作为STRING,SORTORDER作为INT)。 Because things always change, this avoids hard coding anything and is the solution I would recommend for real world use. 因为事情总是在变化,这避免了硬编码任何东西,并且是我推荐用于现实世界的解决方案。
If you don't want the flexibility of adding new terms and orders, just use a CASE statement to transform each term into an number: 如果您不希望添加新条款和订单的灵活性,只需使用CASE语句将每个术语转换为数字:
CASE A WHEN 'stack' THEN 1 WHEN 'over' THEN 2 WHEN 'flow' THEN 3 END
and use it in your ORDER BY. 并在你的ORDER BY中使用它。
If you have alot of elements with custom ordering, you could add those elements to a table and give them a value. 如果您有很多具有自定义排序的元素,则可以将这些元素添加到表中并为其赋值。 Join with the table and each column can have a custom order value. 加入表格,每列可以有一个自定义订单值。
select
main.a,
main.b,
main.c
from dbo.tblMain main
left join tblOrder rank on rank.a = main.a
order by rank.OrderValue
If you have only 3 elements as suggested in your question, you could use a case in the order by... 如果您的问题中只有3个元素,那么您可以按顺序使用案例...
select
*
from dbo.tblMain
order by case
when a='stack' then 1
when a='flow' then 2
when a='over' then 3
else 4
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.