Problem
I need to filter a set of records conditionally. The rules for filter the data are: find duplicate values by ProductNumber and also they need to have a least two ProductType (1 and 5)
Example
Product
| ProductNumber | ProductType | ProductName |
|---|---|---|
| A-000217 | 1 | stuff 13 |
| A-000217 | 5 | stuff 13 |
| A-000086 | 5 | stuff 2 |
| A-000086 | 5 | stuff 2 |
| A-001229 | 1 | stuff 20 |
| A-001146 | 5 | stuff 21 |
| A-001146 | 1 | stuff 21 |
This should be the output
Product (Filtered)
| ProductNumber | ProductType | ProductName |
|---|---|---|
| A-000217 | 1 | stuff 13 |
| A-000217 | 5 | stuff 13 |
| A-001146 | 5 | stuff 21 |
| A-001146 | 1 | stuff 21 |
- Product A-000086 has been excluded because both records are type 5.
- Product A-001229 only has 1 record so it must be excluded.
I tried this code, but it didn't work as expected.
CREATE TABLE #Product(
[Id] [int] IDENTITY(1,1) NOT NULL,
[ProductNumber] [varchar](60) NOT NULL,
[ProductType] [int] NOT NULL,
[ProductName] [varchar](60) NOT NULL,
PRIMARY KEY(Id)
);
INSERT INTO [#Product]([ProductNumber], [ProductType], [ProductName])
VALUES('A-000217', 1, 'stuff 13')
,('A-000217', 5, 'stuff 13')
,('A-000086', 5, 'stuff 2')
,('A-000086', 5, 'stuff 2')
,('A-001229', 1, 'stuff 20')
,('A-001146', 5, 'stuff 21')
,('A-001146', 1, 'stuff 21')
--Filter data
; WITH CTE AS (
SELECT
ProductNumber
, ProductType
, ProductName
, COUNT(ProductType) OVER(PARTITION BY ProductNumber) AS [RowNumber]
FROM #Product
)
SELECT * FROM CTE WHERE RowNumber > 1
Result:
What's wrong with my code? Or how can I achieve this approach?
