Sql server 如何编写SQL SELECT语句以返回ColumnA值,其中ColumnB值仅为x和y以及z
希望有人能够帮助我完成我认为可能是相当简单的T-SQL语句 使用下面的表“ProductCommissionRates”,我试图编写一条sql语句,该语句将返回表中的所有“ProdCode”行,其中“ProdCode”具有“CommRate”=“20”、“25”和“30”。因此,在下面的示例中,我希望只返回'ProdCode'=07053的行Sql server 如何编写SQL SELECT语句以返回ColumnA值,其中ColumnB值仅为x和y以及z,sql-server,tsql,Sql Server,Tsql,希望有人能够帮助我完成我认为可能是相当简单的T-SQL语句 使用下面的表“ProductCommissionRates”,我试图编写一条sql语句,该语句将返回表中的所有“ProdCode”行,其中“ProdCode”具有“CommRate”=“20”、“25”和“30”。因此,在下面的示例中,我希望只返回'ProdCode'=07053的行 ProdCode CommRate RateDesc 00130 10 Desc 17 00130 20
ProdCode CommRate RateDesc
00130 10 Desc 17
00130 20 Desc 18
00130 25 Desc 19
00130 28 Desc 20
00130 30 Desc 21
00130 50 Desc 23
07053 20 Desc 11
07053 25 Desc 12
07053 30 Desc 13
07246 20 Desc 5
07246 25 Desc 6
07246 30 Desc 7
07246 50 Desc 8
07493 20 Desc 1
07493 25 Desc 2
07493 30 Desc 3
07493 50 Desc 4
如果您只需要产品代码列表,可以尝试以下操作。请注意,您没有给我们任何易于使用的数据,因此我创建了最小值来回答您的问题
CREATE TABLE #t1(Prodcode varchar(10),CommRate int)
INSERT INTO #t1 VALUES('00130', 10)
INSERT INTO #t1 VALUES('00130', 25)
INSERT INTO #t1 VALUES('00130', 28)
INSERT INTO #t1 VALUES('00130', 30)
INSERT INTO #t1 VALUES('00130', 50)
INSERT INTO #t1 VALUES('07053', 20)
INSERT INTO #t1 VALUES('07053', 25)
INSERT INTO #t1 VALUES('07053', 30)
INSERT INTO #t1 VALUES('07246', 20)
INSERT INTO #t1 VALUES('07246', 25)
INSERT INTO #t1 VALUES('07246', 30)
INSERT INTO #t1 VALUES('07246', 50)
SELECT Prodcode
FROM #t1
WHERE CommRate in (20,25,30)
GROUP BY Prodcode
HAVING COUNT(*) = 3
EXCEPT
SELECT DISTINCT ProdCode
FROM #t1
WHERE CommRate NOT IN (20,25,30)
如果需要获取所有这些行的描述,请将其放入CTE中,并将其连接回表,如下所示:
;WITH CTE AS
(
SELECT Prodcode
FROM #t1
WHERE CommRate in (20,25,30)
GROUP BY Prodcode
HAVING COUNT(*) = 3
EXCEPT
SELECT DISTINCT ProdCode
FROM #t1
WHERE CommRate NOT IN (20,25,30)
)
SELECT tmp.*
FROM #t1 tmp
INNER JOIN CTE t2 on tmp.Prodcode = t2.Prodcode
如果您只对
ProdCode
感兴趣,请使用以下方法:
select ProdCode
from ProductCommissionRates
group by ProdCode
having
count(distinct case when CommRate in (20, 25, 30) then CommRate end) = 3
and
count(distinct CommRate) = 3
如果还需要表中的整行,则:
select * from ProductCommissionRates
where ProdCode in (
select ProdCode
from ProductCommissionRates
group by ProdCode
having
count(distinct case when CommRate in (20, 25, 30) then CommRate end) = 3
and
count(distinct CommRate) = 3
)
请参阅。结果:
“使用下表‘ProductCommissionRates’”我们不能使用该表;这是图像而不是文本。如果您提供的示例数据必须至少是
文本
,以便我们可以复制和使用它。00130还有commRate20、25、30
,为什么要将其排除在外?您使用的是哪个版本的SQL Server?prodCode是否可以具有两倍相同的commRate?您需要什么输出?只有一个ProdCode列表还是所有行?
> ProdCode | CommRate | RateDesc
> -------: | -------: | :-------
> 7053 | 20 | Desc 11
> 7053 | 25 | Desc 12
> 7053 | 30 | Desc 13