子查询中需要有子查询

时间:2019-07-03 13:28:55

标签: postgresql

我有一个stock表,例如保存

 Partnumber | Depot | flag_redundant
------------+-------+----------------
          1 |     1 |              5
          1 |     2 |              0
          1 |     3 |              0              
          1 |     4 |              5
          2 |     1 |              0
          2 |     2 |              0
          2 |     3 |              0
          2 |     4 |              0

我需要能够看到未将零件标记为冗余的软件仓库,但是flag_redundant至少已被标记为该零件一次,并且我需要忽略那里存在的任何零件尚未被标记。

任何帮助表示赞赏!

我正在考虑....

SELECT stock.part, stock.depot, 
       OrderCount = (SELECT CASE WHEN Stock.flag_redundant = 5 THEN 1 end as Countcolumn FROM stock C)
  FROM stock 

 Partnumber | MissingDepots
------------+---------------
          1 | Yes

2 个答案:

答案 0 :(得分:0)

假设您要获取包含数据集partnumber = flag_redundant5的这些0

demo:db<>fiddle

 SELECT 
    partnumber,
    'Yes' AS missing
FROM (
    SELECT
        partnumber,
        COUNT(flag_redundant) FILTER (WHERE flag_redundant = 5) AS cnt_redundant,   -- 2
        COUNT(*) AS cnt                                                             -- 3
    FROM
       stock
    GROUP BY partnumber                                                             -- 1
) s
WHERE cnt_redundant > 0                                                             -- 4
   AND cnt_redundant < cnt                                                          -- 5
  1. partnumber分组
  2. 计算所有记录,其中flag_redundant = 5
  3. 计算所有记录
  4. 找到所有包含5个元素的所有partnumber
  5. ...且具有比5元素记录更多的记录

答案 1 :(得分:0)

您可以按零件号分组并在HAVING子句中设置条件:

select 
  partnumber, 'Yes' MissingDepots 
from stock 
group by partnumber
having 
  sum(flag_redundant) > 0 and 
  sum(case when flag_redundant = 0 then 1 end) > 0 

或者:

select 
  partnumber, 'Yes' MissingDepots 
from stock 
group by partnumber
having sum(case when flag_redundant = 0 then 1 end) between 1 and count(*) - 1 

请参见demo
结果:

> partnumber | missingdepots
> ---------: | :------------
>          1 | Yes