我有一个正在运行的查询...但是我希望能够以特定方式排序/排序。 我当前的查询(例如)返回如下日期:
CenterID, OrgName, ID, Relationship, REL_START_YEAR, REL_END_YEAR, Full_Name
(84864, 'Twin Cities Spine Center', '19100', 'Fellow', '1971', '1971', 'Robert B. Winter, MD'),
(84864, 'Twin Cities Spine Center', '19100', 'Founder', '1971', '1972', 'Robert C. Summer, MD'),
(84864, 'Twin Cities Spine Center', '19100', 'Faculty', '1971', '1974', 'Robert D. Spring, MD'),
(84864, 'Twin Cities Spine Center', '19100', 'Fellow', '1972', '1974', 'Robert A. Fall, MD'),
(84864, 'Twin Cities Spine Center', '19100', 'Faculty', '1975', '1976', 'Ginger B. Jones, MD'),
(84864, 'Twin Cities Spine Center', '19100', 'Founder', '1977', '1978', 'Mary F. Johnson, MD'),
(84864, 'Twin Cities Spine Center', '19100', 'Faculty', '1971', '1972', 'Shawn S. Dimmer, MD'),
(84864, 'Twin Cities Spine Center', '19100', 'Fellow', '1978', '1978', 'Scotty B. Raw, MD'),
(84864, 'Twin Cities Spine Center', '19100', 'Fellow', '1978', '1981', 'Lou V. Louis, MD'),
(84864, 'Twin Cities Spine Center', '19100', 'Founder', '1984', '1984', 'Paula L. Davis, MD'),
(84864, 'Twin Cities Spine Center', '19100', 'Fellow', '1981', '1982', 'Nadine H. Ericson, MD');
但是我想分类/订购/分组
首先由关系列...但不只是在alpha排序..我希望它被列为
创始人第一 教师第二名 第三名......
然后按REL_START_YEAR
对上面的每个“组”进行排序这让我接近......但不是对关系列顺序的精细控制:
SELECT o.CenterID
, o.OrgName
, r.ID
, r.Relationship
, r.REL_START_YEAR
, r.REL_END_YEAR
, u.ID
, u.Full_Name
FROM genealogy_orgs o
JOIN genealogy_relations r
ON r.CenterID = o.CenterID
JOIN genealogy_users u
ON u.ID = r.ID
WHERE o.CenterID = 84864
ORDER
BY r.Relationship DESC
, r.REL_START_YEAR ASC;
为了能够按关系列中的唯一订单排序/分组,我在寻找什么?某种使用IN()函数?
答案 0 :(得分:1)
创始人第一任教师第二名研究员第三名。
ORDER BY CASE Relationship
WHEN 'Founders' THEN 1 WHEN 'Faculty' THEN 2 WHEN 'Fellow' THEN 3 ELSE 4 END,
REL_START_YEAR -- Not entirely sure what your requirements are here..
答案 1 :(得分:1)
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(relationship VARCHAR(12) NOT NULL
,year INT NOT NULL
,PRIMARY KEY (relationship,year)
);
INSERT INTO my_table VALUES
('Fellow' ,1971),
('Founder',1971),
('Faculty',1971),
('Fellow' ,1972),
('Faculty',1975),
('Founder',1977),
('Faculty',1974),
('Fellow' ,1978),
('Founder',1984),
('Fellow' ,1981);
SELECT *
FROM my_table
ORDER
BY FIELD(relationship,'Founder','Faculty','Fellow')
, year;
+--------------+------+
| relationship | year |
+--------------+------+
| Founder | 1971 |
| Founder | 1977 |
| Founder | 1984 |
| Faculty | 1971 |
| Faculty | 1974 |
| Faculty | 1975 |
| Fellow | 1971 |
| Fellow | 1972 |
| Fellow | 1978 |
| Fellow | 1981 |
+--------------+------+
但请注意,你可以在应用程序代码(php / javascript等)中处理这类事情。