尝试在表中查找重复值时出现 SQL 输出错误

SQL output error when try to find duplicate value in a table

提问人:pika 提问时间:5/31/2022 最后编辑:pika 更新时间:6/1/2022 访问量:243

问:

select

count([Item Nbr]) as [Item Nbr],

count([Item Flags]) as [Item Flags],

count(UPC) as UPC,

count([Store Nbr]) as [Store Nbr] ,

count (RetrievalWeek) as RetrievalWeek,

* from tblStoreItemForecast

GROUP BY

[Item Nbr],[Item Flags],UPC,

[Store Nbr], [Week 01 Forecast], [Week 02 Forecast],

[Week 03 Forecast],[Week 04 Forecast],[Week 05 Forecast],

[Week 06 Forecast],[Week 07 Forecast],[Week 08 Forecast],[Week 09 Forecast],

[Week 10 Forecast],[Week 11 Forecast],[Week 12 Forecast],[Week 13 Forecast],

[Week 14 Forecast],[Week 15 Forecast],RetrievalWeek

having (count(*) > 1)

order by RetrievalWeek desc

我收到消息错误 Msg 8120,

级别 16,状态 1,第 76 行

列“tblStoreItemForecast.Week 16 Forecast”在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。

消息 209,级别 16,状态 1,第 91 行

不明确的列名称“RetrievalWeek”。

谁能帮我为什么会这样。

我尝试了另一种方法

如果我运行下面的代码,它不会给我任何结果,因为我在这里使用记录编号(唯一键)

select

[Item Nbr],[Item Flags],UPC,[Store Nbr],RetrievalWeek,recordno,COUNT(*)

from tblStoreItemForecast

GROUP BY

[Item Nbr],[Item Flags],UPC,[Store Nbr],

RetrievalWeek,recordno

having

count(*) > 1

order by RetrievalWeek desc

但是如果我在不使用记录的情况下运行以下代码,因为它在这里是唯一的 给出结果

select

[Item Nbr],[Item Flags],UPC,[Store Nbr],RetrievalWeek,COUNT(*)

from tblStoreItemForecast

GROUP BY

[Item Nbr],[Item Flags],UPC,[Store Nbr],

RetrievalWeek

having

count(*) > 1

order by RetrievalWeek desc

我想使用记录来计算重复项,没有怎么写,无法弄清楚我也使用内部连接,但是日志中的错误空间无法重用。有什么解决办法吗?

sql sql-server sql-server-2005 重复唯一

评论

1赞 HoneyBadger 5/31/2022
这看起来像 sql server,而不是您标记的 mysql。错误也很清楚,你有什么不明白的?
0赞 Thom A 5/31/2022
我删除了冲突的标签;编辑您的问题以适当地重新标记。
1赞 nacho 5/31/2022
删除 SELECT 中的 *
1赞 Thom A 5/31/2022
那为什么不使用窗口计数呢?在同一列上聚合和分组始终是缺陷的标志。
2赞 Sean Lange 5/31/2022
老实说,看起来你在这里有点设计缺陷。您使用重复组违反了 1NF。[第01周预测]等通过在列名称中放置空格,您还使自己更加困难。按每列排序的分组表明您的表也缺少主键。

答:

0赞 user19231494 5/31/2022 #1

您有一个与表列同名的输出列别名。尝试添加下划线以区分,如下所示。

select

count([Item Nbr]) as [Item Nbr],

count([Item Flags]) as [Item Flags],

count(UPC) as UPC,

count([Store Nbr]) as [Store Nbr] ,

count (RetrievalWeek) as Retrieval_Week,

* from tblStoreItemForecast

GROUP BY

[Item Nbr],[Item Flags],UPC,

[Store Nbr], [Week 01 Forecast], [Week 02 Forecast],

[Week 03 Forecast],[Week 04 Forecast],[Week 05 Forecast],

[Week 06 Forecast],[Week 07 Forecast],[Week 08 Forecast],[Week 09 Forecast],

[Week 10 Forecast],[Week 11 Forecast],[Week 12 Forecast],[Week 13 Forecast],

[Week 14 Forecast],[Week 15 Forecast],RetrievalWeek

having (count(*) > 1)

order by RetrievalWeek desc