0

我是 SQL 新手,并试图用其他语言编写类似于“for 循环”的语句,但被卡住了。我想在不使用函数的情况下过滤掉所有属性 1、attribute2=attribute3 的表行。

例如:

    | Year | Month | Day|
    | 1  | 1    | 1 |
    | 1  | 2    | 2 |
    | 1  | 4    | 4 |
    | 2  | 3    | 4 |
    | 2  | 3    | 3 |
    | 2  | 4    | 4 |
    | 3  | 4    | 4 |
    | 3  | 4    | 4 |
    | 3  | 4    | 4 |

我只想要行

    | Year | Month | Day|
    |:---- |:------:| -----:|
    | 3  | 4    | 4 |

因为对于它们共享的所有年份值,它是唯一一个月份和日期相等的地方。

到目前为止,我已经从月 = 日的日期中选择年、月、日,但不确定如何对全年应用约束

4

2 回答 2

1
-- month/day need to appear in aggregate functions (since they are not in the GROUP BY clause),
-- but the HAVING clause ensure we only have 1 month/day value (per year) here, so MIN/AVG/SUM/... would all work too
SELECT year, MAX(month), MAX(day)
FROM my_table
GROUP BY year
HAVING COUNT(DISTINCT (month, day)) = 1;
最大限度 最大限度
3 4 4

在 DB Fiddle 上查看

于 2021-03-13T22:29:01.853 回答
0

所以一种方法是

select distinct [year], [month], [day]
from [Table] t
where [month]=[day]
and not exists (
  select * from [Table] x
  where t.[year]=x.[year] and t.[month] <> x.[month] and t.[day] <> x.[day]
)

另一种方法是

select distinct [year], [month], [day] from (
    select *,
        Lead([month],1) over(partition by [year] order by [month])m2,
        Lead([day],1) over(partition by [year] order by [day])d2
    from [table]
)x
where [month]=m2 and [day]=d2
于 2021-03-13T22:18:05.863 回答