【问题标题】:Cannot use window function 'count' in having statement在有语句中不能使用窗口函数“计数”
【发布时间】:2020-06-17 06:03:49
【问题描述】:

我是 MYSQL 的新手,我正在尝试验证 2 列中出现多次的同名数据的数量,在这种情况下我已经尝试使用“有”语句,并且它给我一个这样的错误 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

【问题讨论】:

  • 我也不能使用“where”语句。所以似乎没有办法验证它
  • 我相信 WINDOW 函数只允许在 SELECT/ORDER 子句中使用。

标签: mysql sql count mysql-workbench having-clause


【解决方案1】:

您不能使用拥有和窗口功能。您可能希望执行以下操作

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

【讨论】:

    【解决方案2】:
    SELECT {fieldset}
    FROM {tableset}
    WHERE {conditions-1}
    GROUP BY {expression-1}
    HAVING {conditions-2}
       AND {expression-2} = COUNT({expression-3}) OVER ({window})
    

    窗口函数应用于输出数据集,但 HAVING 改变了它。所以窗口函数不能在 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`
    

    【讨论】:

      猜你喜欢
      • 2011-05-20
      • 2022-08-18
      • 2014-08-24
      • 2018-08-10
      • 2020-02-09
      • 2021-08-26
      • 2021-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多