[英]SQL Order by using the values from two different columns
Suppose I have a table NAME with the columns PART_TYPE and VALUE. 假设我有一个名为NAME的表,该表的列为PART_TYPE和VALUE。 Each type can have multiple types like FAMILY, GIVEN, PREFIX, etc.
每种类型都可以具有多种类型,例如FAMILY,GIVEN,PREFIX等。
What I would like to do is write SQL to get all the names but have them first ordered by a specific type then have them ordered alphabetically within that type. 我想做的是编写SQL来获取所有名称,但先按特定类型对它们进行排序,然后在该类型内按字母顺序对它们进行排序。
I have something like this: 我有这样的事情:
SELECT *
FROM name
ORDER BY (
CASE
WHEN PART_TYPE = 'GIV'
THEN VALUE
END)
But I'm not sure how to include the other types as a primary order while keeping the VALUE as the secondary order. 但是我不确定如何将其他类型作为主要顺序,同时将VALUE保留为次要顺序。 Adding another case statement will then just make VALUE the primary order.
添加另一个case语句将使VALUE成为主要订单。
I would like to keep this database independent but if need be, I would be willing to make it Oracle specific. 我想使该数据库独立,但是如果需要,我愿意使其成为Oracle专用的。
How can I do this? 我怎样才能做到这一点? Also, a way of doing this with Hibernate Criteria would also be greatly appreciated.
同样,使用Hibernate Criteria进行此操作的方法也将受到极大的赞赏。
Edit: I need the PART_TYPE to be ordered by a specific order as defined by me. 编辑:我需要按照我定义的特定顺序对PART_TYPE进行排序。 In particular, it needs to be GIVEN then FAMILY.
特别是,必须先给予家庭。
So it should look like this: 所以它应该看起来像这样:
GIVEN A
GIVEN B
GIVEN C
FAMILY A
FAMILY B
The natural order by would have FAMILY first, not GIVEN. 自然顺序是家庭优先,而不是给予家庭。
The most manageable way of resolving this is probably to have a table containing all your Types, and then a sort column within that. 解决此问题的最可管理的方法可能是拥有一个包含所有类型的表,然后在其中包含一个排序列。 So you might have a table like:
因此,您可能有一个像这样的表:
TypeID Name SortOrder
1 FAMILY 2
2 GIVEN 1
3 PREFIX 3
Then you Can join this on to your query and use: 然后,您可以将其加入查询并使用:
ORDER BY SortOrder, Value
You could just resolve this with a CASE
expression 您可以使用
CASE
表达式解决此问题
ORDER BY CASE Type
WHEN 'GIVEN' THEN 1
WHEN 'FAMILY' THEN 2
WHEN 'PREFIX' THEN 3
END,
Value
But the more types you have the less manageable the case expression becomes. 但是,类型越多,case表达式变得越难管理。
SELECT *
FROM name
ORDER BY
CASE
WHEN TYPE = 'GIVEN' THEN 1
WHEN TYPE = 'FAMILY' THEN 2
ELSE 3
END,
VALUE
This will order the result by a custom order on TYPE and VALUE as the secondary order. 这将根据TYPE和VALUE上的自定义订单对结果进行排序。
ORDER BY CASE TYPE
WHEN 'GIVEN' THEN 0
WHEN 'FAMILY' THEN 1
ELSE 2
END,
VALUE
Feels a bit 'hacky' but it works 感觉有点“ hacky”,但是可以用
SELECT part_type,name
FROM (
SELECT
CASE
WHEN part_type = 'Given' THEN 'A'
WHEN part_type = 'Family' THEN 'B'
END AS Sorthack,
part_type,
name
FROM NAME
) Sort
ORDER BY sorthack,name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.