我有一个显示如下结果的查询:
Zip | Left Price | Right Price
17901 | 100.00 | null
17820 | null | 40.00
54353 | null | null
53133 | 40.00 | 542.00
如何删除左侧和价格均为空的结果。因此我不希望带有zip 54353的那个甚至出现在结果中。
以下是我查询的方式:
SELECT contacts.zip, CASE WHEN
left_return_date IS NULL AND left_delivery_date IS NOT NULL AND left_price
IS NOT NULL THEN left_price ELSE null END AS left_price, CASE WHEN
right_return_date IS NULL AND right_delivery_date IS NOT NULL AND
right_price IS NOT NULL THEN right_price ELSE null END AS right_price
FROM invoice_hearing_aids
LEFT JOIN invoices ON invoices.ID = invoice_hearing_aids.invoice_id
LEFT JOIN contacts ON contacts.id = invoices.contact_id
WHERE
trial_complete = 'Y'
AND invoices.company_id = '1'
AND invoices.date_issued >= DATE_SUB(NOW(),INTERVAL 1 YEAR)
答案 0 :(得分:0)
您最后可以添加HAVING
子句,如下所示:
SELECT contacts.zip, CASE WHEN
left_return_date IS NULL AND left_delivery_date IS NOT NULL AND left_price
IS NOT NULL THEN left_price ELSE null END AS left_price, CASE WHEN
right_return_date IS NULL AND right_delivery_date IS NOT NULL AND
right_price IS NOT NULL THEN right_price ELSE null END AS right_price
FROM invoice_hearing_aids
LEFT JOIN invoices ON invoices.ID = invoice_hearing_aids.invoice_id
LEFT JOIN contacts ON contacts.id = invoices.contact_id
WHERE
trial_complete = 'Y'
AND invoices.company_id = '1'
AND invoices.date_issued >= DATE_SUB(NOW(),INTERVAL 1 YEAR)
HAVING
right_price IS NOT NULL OR left_price IS NOT NULL
如果您拥有相对较少的此类不需要的记录(这样做最多可达到总结果集大小的50%),这样可以正常工作。如果有更多此类记录,那么我会更接近查询,并且很可能会修改条件。
答案 1 :(得分:0)
请确保left_price和right_price是您可以添加条件
的列值 SELECT contacts.zip,
CASE WHEN left_return_date IS NULL
AND left_delivery_date IS NOT NULL
AND left_price IS NOT NULL THEN left_price
ELSE null END AS left_price,
CASE WHEN right_return_date IS NULL
AND right_delivery_date IS NOT NULL
AND right_price IS NOT NULL THEN right_price
ELSE null END AS right_price
FROM invoice_hearing_aids
LEFT JOIN invoices ON invoices.ID = invoice_hearing_aids.invoice_id
LEFT JOIN contacts ON contacts.id = invoices.contact_id
WHERE
trial_complete = 'Y'
AND invoices.company_id = '1'
AND invoices.date_issued >= DATE_SUB(NOW(),INTERVAL 1 YEAR)
AND NOT (left_price IS NULL AND right_price IS NULL)