2013-08-16 58 views
1

在我的圖像分類軟件中有表resultimage其中一個結果可以包含許多圖像。 每個圖像可在列image.preclassification僅從子表中選擇只有行滿足條件的子錶行

結果,其中多個圖像是正爲正使用值「P」或「N」被歸類爲

我想只選擇積極的結果。

閱讀Postgres的文檔了幾個小時後,我來到了這樣的解決方案,它讓我害怕:

WITH tmp AS (
SELECT result.result_id AS res, image.result_id , Count(image.preclassification) AS ImgAll, 
SUM(
CASE image.preclassification 
    WHEN 'P' THEN 1 
    ELSE 0 
END 
) AS ImgPos 

from result, image 
WHERE result.result_id = image.result_id 
GROUP BY result.result_id, image.result_id 
) 
SELECT result_id 
FROM tmp 
WHERE ImgPos > ImgAll/2 

我的問題是,是否有這樣的(ihmo很常見)問題的一個簡單的解決方案/辦法?

編輯:說明

首先,我創建一個包含正面形象的數列和計數結果的所有圖像臨時表。在下一步中,我只選擇行,正面圖像的數量多於所有圖像的一半。我的第一個想法是在第一個WHERE聲明中使用ImgPos > ImgAll/2,而不是使用WITH-條款。但它並沒有像ImgPos那樣工作,ImgAll被報告爲未知列。

回答

2

聰明的查詢。但我認爲你可以把它簡化:

select r.result_id 
from result r join 
    image i 
    on r.result_id = i.result_id 
group by r.result_id 
having sum(case when i.preclassification = 'P' then 1 else 0 end) > 
     sum(case when i.preclassification = 'N' then 1 else 0 end); 

你也可以寫爲:

select r.* 
from (select r.result_id, 
      sum(case when i.preclassification = 'P' then 1 else 0 end) as NumPos, 
      sum(case when i.preclassification = 'N' then 1 else 0 end) as NumNeg 
     from result r join 
      image i 
      on r.result_id = i.result_id 
     group by r.result_id 
    ) r 
where NumPos > NumNeg; 
+0

+1太好了,謝謝!兩者都很好! (只需要在第三版中用i替代第二版中的第四版)。我想我會採取你的第一個建議,因爲它看起來更容易:-) –

1

我可能會做一些像這兩個查詢:

以1:

select * 
from result r 
join (select t.result_id 
     from result t 
     join image i on i.result_id = t.result_id 
     group by t.result_id 
     having sum(case i.preclassification when 'P' then 1 else 0 end) > 
       sum(case i.preclassification when 'N' then 1 else 0 end) 
    ) s on s.result_id = r.result_id 

取2:

select r.*, p.frequence as positives , n.frequency as negatives 
from result r 
join  (select t.result_id , count(*) as frequency 
      from result t 
      join image i on i.result_id = r.result_id 
         and i.preclassification = 'P' 
     ) p on r.result_id = p.result_id 
left join (select t.result_id , count(*) as frequency 
      from result t 
      join image i on i.result_id = r.result_id 
         and i.preclassification = 'N' 
     ) n on n.result_id = r.result_id 
where p.frequency > coalesce(n.frequency, 0) 

積極派生表的內連接是因爲必須至少有一個肯定的結果是肯定的;否定派生表上的外連接是因爲你根本不需要任何否定。

+0

+1:有趣,謝謝!我已經修復了第一個例子,它可以工作,但無法獲得第二個運行。 –

1

另一種方式來做到這一點是 - 只爲圖「積極的」正和「負」負:)

select r.result_id 
from result as r 
    inner join image as i on r.result_id = i.result_id 
group by r.result_id 
having sum(case i.preclassification when 'P' then 1 when 'N' then -1 end) > 0 
+0

+1:酷!作品也。我是格拉斯我問過這個問題。我從所有答案中學到了很多:-) –

相關問題