不能在 having 语句中使用 window 函数 'count'

Cannot use window function 'count' in having statement

我是 MYSQL 的新手,我正在尝试验证出现不止一次的 2 列中具有相同名称的数据的数量,我已经尝试使用它 'having' 声明在这种情况下,它会抛出这样的错误 Error Code: 3593. You cannot use the window function 'count' in this context.' 下面我附上了我正在尝试做的事情的图片

您可以看到名为 "number_of_same_year" 的列表示 "COUNT OVER PARTITION" 输出,其中包含逻辑上可以验证的数字。我只想显示数字大于 1 的位置(这意味着出现不止一次)

ps:我在 Windows 10

中使用 MySQL

您不能使用 having 和 window 函数。您可能希望改为执行以下操作

select * from (
select unit_name
       ,month(transaction_date)
       ,year(transaction_date) as year
       ,budget
       ,count(*) over(partition by unit_name,year(transaction_date)) as number_of_same_year
  from sql_advertising.history_transaction
  )x
where x.number_of_same_year >1
order by x.unit_name
SELECT {fieldset}
FROM {tableset}
WHERE {conditions-1}
GROUP BY {expression-1}
HAVING {conditions-2}
   AND {expression-2} = COUNT({expression-3}) OVER ({window})

Window 函数应用于输出数据集,但 HAVING 改变了它。所以window函数不能用在HAVING中。以上代码无效。

您可以通过以下方式解决:

WITH `cte` AS ( SELECT {fieldset}, 
                       {expression-2} = COUNT({expression-3}) OVER ({window}) AS `criteria`
                FROM {tableset}
                WHERE {conditions-1}
                GROUP BY {expression-1}
                HAVING {conditions-2} )
SELECT {fieldset}
FROM `cte`
WHERE `criteria`