问题
i create the query
SELECT Dt, CustomerName, ItemRelation, SaleCount,
DocumentNum, DocumentYear, IsPromo, CustomerType
FROM [dbo].[promo_data] where [CustomerType]='XY'
there is data on the stock [IsPromo] (0-no stock, 1 is a stock) how can i select only these obs XY of CustomerType which have only one value 1 for the action category = 1
simple example
[ItemRelation] [SaleCount] IsPromo ,[DocumentNum] [DocumentYear]
11203 8,85947691 0 138 2018
11203 9,450108704 0 138 2018
11203 12,40326767 1 138 2018
11202 8,85947691 0 137 2018
11202 9,450108704 0 137 2018
11202 12,40326767 1 137 2018
11202 25,98779894 1 137 2018
11202 63,19760196 1 137 2018
i must select
11203 1 138 2018
because
11202 137 2018
has two ones
回答1:
You seem to want:
SELECT ItemRelation, DocumentNum, DocumentYear, IsPromo
FROM [dbo].[promo_data]
WHERE CustomerType = 'XY' AND IsPromo = 1
GROUP BY ItemRelation, DocumentNum, DocumentYear, IsPromo
HAVING COUNT(*) = 1;
EDIT:
To retrieve all columns, use window functions:
SELECT *
FROM (SELECT pd.*,
COUNT(*) OVER (PARTITION BY ItemRelation, DocumentNum, DocumentYear, IsPromo) as cnt
FROM [dbo].[promo_data] pd
WHERE CustomerType = 'XY' AND IsPromo = 1
) pd
WHERE cnt = 1;
回答2:
Based on Gordon's answer, if you want to select additional fields not used in grouping, you could do a self-join with a subquery, like this:
SELECT pd.Dt, pd.CustomerName, pd.ItemRelation, pd.SaleCount,
pd.DocumentNum, pd.DocumentYear, pd.IsPromo, pd.CustomerType
FROM [dbo].[promo_data] pd
INNER JOIN(
SELECT ItemRelation, DocumentNum, DocumentYear, IsPromo
FROM [dbo].[promo_data]
WHERE CustomerType = 'XY' AND IsPromo = 1
GROUP BY ItemRelation, DocumentNum, DocumentYear, IsPromo
HAVING COUNT(*) = 1
) grouped
ON pd.ItemRelation = grouped.ItemRelation
AND pd.DocumentNum = grouped.DocumentNum
AND pd.DocumentYear = grouped.DocumentYear
AND pd.IsPromo = grouped.IsPromo
来源:https://stackoverflow.com/questions/50837090/sql-how-to-sort-values-into-categories-in-ssms