我有一个查询来提取驱动程序名称和终端号码 这里:
SELECT UNIQUE D.DRIVER_ID, D.NAME,
CASE
WHEN TERMINAL_NUMBER = '0' THEN 'LITHONIA'
WHEN TERMINAL_NUMBER = '1' THEN 'MONTGOMERY'
WHEN TERMINAL_NUMBER = '2' THEN 'BOWLING GREEN'
WHEN TERMINAL_NUMBER = '4' THEN 'OOLTEWAH'
WHEN TERMINAL_NUMBER = '40' THEN 'LEXINGTON SOUTH'
WHEN TERMINAL_NUMBER = '41' THEN 'DURHAM'
WHEN TERMINAL_NUMBER = '42' THEN 'LEXINGTON'
WHEN TERMINAL_NUMBER = '43' THEN 'OKC'
WHEN TERMINAL_NUMBER = '46' THEN 'STEVENSON'
WHEN TERMINAL_NUMBER = '47' THEN 'TUPELO'
WHEN TERMINAL_NUMBER = '48' THEN 'HUMBOLDT'
WHEN TERMINAL_NUMBER = '49' THEN 'MURFREESBORO'
WHEN TERMINAL_NUMBER = '5' THEN 'JEFFERSON CTIY'
WHEN TERMINAL_NUMBER = '50' THEN 'LEWISBURG'
WHEN TERMINAL_NUMBER = '52' THEN 'SAVANNAH'
WHEN TERMINAL_NUMBER = '54' THEN 'FRANKLIN'
WHEN TERMINAL_NUMBER = '6' THEN 'JACKSONVILLE'
WHEN TERMINAL_NUMBER = '75' THEN 'VIRGINIA'
WHEN TERMINAL_NUMBER = '8' THEN 'ATHENS'
WHEN TERMINAL_NUMBER = '9' THEN 'LATTA'
WHEN OTHER_CODE = 'COL' THEN 'COLOMBUS'
END AS TERM
FROM DRIVER D
WHERE D.ACTIVE_IN_DISP = 'True'
ORDER BY DRIVER_ID, term
但是,我需要让colombus
成为自己的“term
”列,唯一的问题是可能有其他code = 'col'
的驱动程序也在终端0中。
我应该如何重写此查询以证明这一点?
答案 0 :(得分:2)
这是进行此类翻译的更好方法 - 我使用VALUES语句创建一个“临时”表,然后加入该表。我认为这清楚地说明了如何将这些数据存储在一个更好的表中。
SELECT UNIQUE D.DRIVER_ID, D.NAME, TERMLIST.NAME AS TERM
FROM DRIVER D
LEFT JOIN (
VALUES
('0' , 'LITHONIA' ),
('1' , 'MONTGOMERY' ),
('2' , 'BOWLING GREEN'),
('4' , 'OOLTEWAH'),
('40', 'LEXINGTON SOUTH'),
('41', 'DURHAM'),
('42', 'LEXINGTON'),
('43', 'OKC'),
('46', 'STEVENSON'),
('47', 'TUPELO'),
('48', 'HUMBOLDT'),
('49', 'MURFREESBORO'),
('5' , 'JEFFERSON CTIY'),
('50', 'LEWISBURG'),
('52', 'SAVANNAH'),
('54', 'FRANKLIN'),
('6' , 'JACKSONVILLE'),
('75', 'VIRGINIA'),
('8' , 'ATHENS'),
('9' , 'LATTA')
) TERMLIST ON TERMLIST.TN = D.TERMINAL_NUMBER
WHERE D.ACTIVE_IN_DISP = 'True'
ORDER BY D.DRIVER_ID, TERMLIST.NAME
对于您对两个值的特殊要求,我们这样做:
SELECT UNIQUE D.DRIVER_ID, D.NAME,
CASE WHEN D.TERMINAL_NUMBER = '0' AND D.OTHER_CODES = 'COL' THEN 'COL'
ELSE TERMLIST.NAME END AS TERM
FROM DRIVER D
LEFT JOIN (
VALUES
('0' , 'LITHONIA' ),
('1' , 'MONTGOMERY' ),
('2' , 'BOWLING GREEN'),
('4' , 'OOLTEWAH'),
('40', 'LEXINGTON SOUTH'),
('41', 'DURHAM'),
('42', 'LEXINGTON'),
('43', 'OKC'),
('46', 'STEVENSON'),
('47', 'TUPELO'),
('48', 'HUMBOLDT'),
('49', 'MURFREESBORO'),
('5' , 'JEFFERSON CTIY'),
('50', 'LEWISBURG'),
('52', 'SAVANNAH'),
('54', 'FRANKLIN'),
('6' , 'JACKSONVILLE'),
('75', 'VIRGINIA'),
('8' , 'ATHENS'),
('9' , 'LATTA')
) TERMLIST ON TERMLIST.TN = D.TERMINAL_NUMBER
WHERE D.ACTIVE_IN_DISP = 'True'
ORDER BY D.DRIVER_ID, TERMLIST.NAME