拉动整个记录限定同一列中的多个值(关系部门)

时间:2017-04-18 20:13:59

标签: teradata

在一个非常简单的例子中,我想提取两个在伦敦驾驶阅读车的车主和白色柴油车的全部记录。不是蓝色汽车的记录,也不是来自科索沃或基辅的汽车。

我提出了2个不完整的解决方案,但到目前为止还未能获得能够解决此问题的准确SQL。

不完整的解决方案#1

select  
  -- * /* will not work */
  owner  
from cars 
where (color ='red' and city='London') or (color='white' and type='diesel')
group by owner
having count(distinct color)=2;

这只给了我所寻找的所有者,但不是完整的记录。如果我定义" red"这也不会使用范围或通配符。 as"浅红色"或"红色"或者"深红色",id est - 颜色类似于'%red%'或者颜色='白色'。

这看起来很粗暴,可能会使用通配符,但仍然没有完整记录。

select  
  owner  
from cars 
where (color ='red' and city='London') or (color='white' and type='diesel')
group by owner
having count(distinct 
  case when color like '%red%' then 1
       when color ='green' then 0
  end)=2;

不完整的解决方案#2

select owner where color like '%red%' and city='London'
intersect 
select owner where color ='white' and type='diesel';   

这很光滑,即使使用通配符也会给我正确的所有者列表,但仍然不允许我提取完整记录,因为它会从中获取汽车柏林,蓝色汽车等 - 如果我选择使用"其中所有者在(...)"条款。

任何想法都会受到高度赞赏,现在已经走了很长一段时间了。

2 个答案:

答案 0 :(得分:2)

select      *  

from        cars 

where       (   color   = 'red'   
            and city    = 'london'
            )
        or  (   color   = 'white' 
            and type    = 'diesel'
            )   

qualify     min (color) over (partition by owner) <>
            max (color) over (partition by owner)

select      *  

from        cars 

where       (   color   = 'red'   
            and city    = 'london'
            )
        or  (   color   = 'white' 
            and type    = 'diesel'
            )   

qualify         max (case when color = 'red'   and city = 'london' then 1 else 0 end) 
                    over (partition by owner)
            +   max (case when color = 'white' and type = 'diesel' then 1 else 0 end) 
                    over (partition by owner)
            =   2

答案 1 :(得分:0)

您可以使用带有QUALIFY窗口函数的COUNT()子句:

SELECT  *  
FROM cars 
WHERE (color ='red' and city='London') or (color='white' and type='diesel')    
QUALIFY COUNT(*) OVER (PARTITION BY owner) = 2

初始记录集由WHERE语句过滤,因此它很有意义。然后QUALIFY在结果上运行并计算每个owner的记录数。如果该计数为2,则允许记录通过。

如果你不熟悉Window Funtions,那么你可能想在结果中抛出这个,这样你就可以看到它出现的数字:

SELECT  cars.*, COUNT(*) OVER (PARTITION BY owner) as count_of_records_for_owner
FROM cars 
WHERE (color ='red' and city='London') or (color='white' and type='diesel')    
/*QUALIFY COUNT(*) OVER (PARTITION BY owner) = 2*/

您将看到最后一个字段显示该特定所有者的记录总数。 Qualify语句只是更进一步,并过滤了该计算的结果。