gpt4 book ai didi

sql - 如何在组中查找重复项 - SQL 2008

转载 作者:搜寻专家 更新时间:2023-10-30 23:10:43 25 4
gpt4 key购买 nike

我有一个包含以下数据的表 (MyTable)。 (按Order_No,Category,Type排序)

Order _No   Category    Type    
Ord1 A Main Unit
Ord1 A Other
Ord1 A Other
Ord2 B Main Unit
Ord2 B Main Unit
Ord2 B Other

我需要做的是,扫描表格,看看是否有任何“类别”有多个“主要单位”。如果是这样,请对整个类别发出警告。预期结果应如下所示。

Order _No   Category    Type      Warning
Ord1 A Main Unit
Ord1 A Other
Ord1 A Other
Ord2 B Main Unit More than one Main Units
Ord2 B Main Unit More than one Main Units
Ord2 B Other More than one Main Units

我尝试了几种方法(使用子查询)来获得结果,但没有成功。请帮忙!!

(Case
When (Select t1.Category
From MyTable as t1
Where MyTable.Order_No = t1.Order_No
AND MyTable.Category = t1. Category
AND MyTable.Type = t1.Type
AND MyTable.Type = ‘Main Unit’
Group by t1. t1.Order_No, t1. Category, t1.Type
Having Count(*) >1) = 1
Then ‘More than one Main Units’
Else ‘’ End ) as Warning

最佳答案

一个选项是使用 COUNT() OVER() 来计算主要单位,按类别划分;

SELECT Order_No, Category, Type, 
CASE WHEN COUNT(CASE WHEN Type='Main Unit' THEN 1 ELSE NULL END)
OVER (PARTITION BY Category) > 1
THEN 'More than one Main Units' ELSE '' END Warning
FROM MyTable

An SQLfiddle to test with .

关于sql - 如何在组中查找重复项 - SQL 2008,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20809456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com