我有三个表:入侵,警报和CCTV,并且我想使用case语句来获取对象的registration_number及其位置,具体取决于它是CCTV还是触发了入侵事件的警报。入侵表。
这是入侵表:
CCTV表类似于警报表,这是我的代码:
SELECT
ALARM_ID
, CCTV_ID
, CASE
WHEN
ALARM_ID IS NULL
AND CCTV_ID IS NOT NULL
THEN
(
SELECT
REGISTRATION_NUMBER, LOCATION
FROM
REMOTE_SECURITY.ALARMS
WHERE
REMOTE_SECURITY.INTRUSIONS.ALARM_ID = REMOTE_SECURITY.ALARMS.ALARM_ID
)
WHEN
ALARM_ID IS NOT NULL
AND CCTV_ID IS NULL
THEN
(
SELECT
REGISTRATION_NUMBER, LOCATION
FROM
REMOTE_SECURITY.CCTVS
WHERE
REMOTE_SECURITY.INTRUSIONS.cctv_id = REMOTE_SECURITY.CCTVS.CCTV_ID
)
ELSE
'not running'
END
FROM
REMOTE_SECURITY.INTRUSIONS
我希望最终输出是一个包含两列的表:Location和Registration_number。 (我不需要知道它是闭路电视还是闹钟)
任何帮助将不胜感激!
答案 0 :(得分:0)
那为什么不做:
SELECT location, registration_number FROM alarms
WHERE alarm_id IN (SELECT alarm_id FROM intrusions)
UNION
SELECT location, registration_number FROM cctvs
WHERE cctv_id IN (SELECT cctv_id FROM intrusions)
这应该基本上与您的代码等效,只是更简洁,更接近您的意图
如果您确实想从intrusions
表中获取信息,则可能是这样的:
SELECT intrusion_id, datetime_occurred,
COALESCE(a.location, c.location) AS location,
COALESCE(a.registration_number, c.registration_number) AS registration_number
FROM intrusions i
LEFT JOIN alarms a ON i.alarm_id = a.alarm_id
LEFT JOIN cctvs c ON i.cctv_id = c.cctv_id
不确定要怎么做才能得到语法错误,这样做对我有用:
create temp table intrusions (intrusion_id serial primary key, datetime_occurred timestamp, alarm_id int, cctv_id int);
create temp table alarms (alarm_id serial primary key, location text, registration_number text);
create temp table cctvs (cctv_id serial primary key, location text, registration_number text);
如果您在问题中包含此类代码,将很有帮助!如果使其他人更容易获得更多答案……