1

在我的图像分类软件中有表格resultimage. 一个结果可以包含许多图像。每个图像可以使用列中的值“P”或负值“N”分类为image.preclassification

结果,更多的图像是正面的就是正面的。

我只想选择积极的结果。

在阅读了几个小时的 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 非常常见)问题,是否有更简单的解决方案/方法?

编辑:解释

首先,我创建一个临时表,其中的列包含正图像的计数和结果的所有图像的计数。在下一步中,我只选择行,正图像的数量超过所有图像的一半。我的第一个想法是ImgPos > ImgAll/2在第一个WHERE语句中使用而不是使用WITH-clause。但它不能作为 ImgPos 工作,ImgAll 被报告为未知列。

4

3 回答 3

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;
于 2013-08-16T22:32:42.450 回答
1

Another way to do it is - just to map "positive" to positive and "negative" to negative :)

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
于 2013-08-17T07:06:34.260 回答
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 )

正数派生表上的内连接是因为您必须至少有一个正数才能使结果为正数;底片派生表上的外连接是因为您根本不需要任何底片。

于 2013-08-16T23:11:36.087 回答