就是這樣。我們按照實體ID對狀態進行分組,並在分組後將其過濾爲只有那些具有MIN和MAX付費的狀態。實體7將具有「取消」的最小值和「已付」的最大值,因此被排除。
SELECT e.*
FROM
entities e
INNER JOIN
(
SELECT entity_id FROM statuses s
GROUP BY entity_id
HAVING
MIN(CASE WHEN status = 'canceled' THEN status ELSE 'not canceled' END) = 'not canceled' AND
MAX(CASE WHEN status = 'paid' then 'paid' ELSE 'not paid' END) = 'paid'
) a
ON
a.entity_id = e.id
多一點的MIN和MAX,按您的評論:
你說的事情可以有很多的狀態,但我們真的只在付費的東西感興趣,那麼我們只有在那些支付感興趣事情,如果他們從來沒有取消。我們做什麼,然後與狀態是:
- 又比「取消」其他一切都變成「不取消」
- 又比其他一切「有償」轉變爲「未支付」
- 鏈接行條目起來和尋找的「有償」配對/「不取消」
要明白我的意思是,看看:
SELECT
entity_id,
CASE WHEN status = 'paid' then 'paid' ELSE 'not paid' END as is_paid,
CASE WHEN status = 'canceled' THEN status ELSE 'not canceled' END as is_cancelled
FROM
status
現在採取LO確定在:
SELECT
entity_id,
MAX(CASE WHEN status = 'paid' then 'paid' ELSE 'other' END) as is_paid,
MIN(CASE WHEN status = 'canceled' THEN status ELSE 'not canceled' END) as is_cancelled
FROM
status
GROUP BY
entity_id
這是一個「透視」操作;它在概念上將行變成列。項目7的多行成爲具有多列的單行。因爲按字母順序,「付費」是在「未付款」之後,「取消」在「
之前」,因此這是我們尋找「已付款」/「未取消」配對的方式。點,我們可以這樣說:
SELECT * FROM entities INNER JOIN
(
SELECT
entity_id,
MAX(CASE WHEN status = 'paid' then 'paid' ELSE 'other' END) as is_paid,
MIN(CASE WHEN status = 'canceled' THEN status ELSE 'not canceled' END) as is_cancelled
FROM
status
GROUP BY
entity_id
) finder
ON
entities.id = finder.entity_ID
WHERE
finder.is_paid = 'paid' and finder.is_canceled = 'not canceled'
這只是一個有點短做這個過濾較早使用具有而不是以後使用WHERE
它似乎這樣做。謝謝! –