我需要使用看起来像这样的表:
Date | Number1 | Number2 | Number 3 --------------------------------------------------------- 29.11.2016 | 7 | 7 | 5 --------------------------------------------------------- 30.11.2016 | 5 | 6 | 7
我需要定义一个函数来遍历表并返回一个布尔值。 TRUE
,如果存在重复值,则Number1,Number2,Number3和FALSE
中没有重复值。问题是,也可能有4号或5号,可以有无限列,函数应该可以处理。
这样做的有效方法是什么?提前谢谢!
答案 0 :(得分:1)
您的数据结构很差。使用列中的值会更容易,所以让我们取消数据并以这种方式进行查询。以下假设date
是不同的:
with t as (
select date, number1 as num from t union all
select date, number2 from t union all
select date, number3 from t
)
select date,
(case when count(*) = count(distinct num) then 'true' else 'false' end) as flag
from t
where num is null
group by date;
作为单一选择,这变得复杂:
select t.*,
(case when number1 in (number2, number3) then 'false'
when number2 in (number3) then 'false'
else 'true'
end) as flag
from t;
好的,那不是那么糟糕。这很容易扩展到多列:
select t.*,
(case when number1 in (number2, number3, number4, number5) then 'false'
when number2 in (number3, number4, number5) then 'false'
when number3 in (number4, number5) then 'false'
when number4 in (number5) then 'false'
else 'true'
end) as flag
from t;
答案 1 :(得分:0)
我认为通过检查最高值和最低值是否相同可以相当简单地解决这个问题:
select
t.*,
case
when Greatest(number1, number2, number3) =
Least(number1, number2, number3)
then 1
else 0
end as no_duplicates
from t;