我正在尝试进一步调整此查询。查询返回每个样本的三个不同测试的状态。但是,如果我希望进一步过滤返回的样本,我必须在两个“SELECT ... FROM sample ...
”查询中添加条件。
是否可以仅引用sample
表重写此查询一次?
SELECT sample_id,
created_on,
s_acid,
s_ph,
s_titr
FROM
(SELECT sample_id, -- Rows w/ same sample_id to columns
MAX (CASE WHEN tst_tmpl_id = 36 THEN status END) AS s_acid,
MAX (CASE WHEN tst_tmpl_id = 43 THEN status END) AS s_ph,
MAX (CASE WHEN tst_tmpl_id = 66 THEN status END) AS s_titr
FROM (SELECT test_id, test_tmpl_id, sample_id FROM test)
JOIN (SELECT sample_id FROM sample WHERE sam_tmpl_id = 18)
USING (sample_id)
GROUP BY sample_id
)
-- get other sample fields
JOIN (SELECT sample_id, created_on FROM sample WHERE sam_tmpl_id = 18)
USING (sample_id)
答案 0 :(得分:3)
WITH q AS
(
SELECT sample_id, created_on
FROM sample
WHERE sam_tmpl_id = 18
)
SELECT sample_id,
created_on,
s_acid,
s_ph,
s_titr
FROM (
SELECT sample_id, -- Rows w/ same sample_id to columns
MAX (CASE WHEN tst_tmpl_id = 36 THEN status END) AS s_acid,
MAX (CASE WHEN tst_tmpl_id = 43 THEN status END) AS s_ph,
MAX (CASE WHEN tst_tmpl_id = 66 THEN status END) AS s_titr
FROM (
SELECT test_id, test_tmpl_id, sample_id
FROM test
)
JOIN q
USING (sample_id)
GROUP BY
sample_id
)
JOIN q
USING (sample_id)