我正在SQL Server 2016 SP1中开发存储过程。
此语句返回重复的值。它将相同的值重复四次:
Select Serial =
CASE al.NumberEncoding
WHEN 3 THEN RIGHT(ex.Serial,LEN(ex.Serial)-2)
ELSE RIGHT(ex.Serial,LEN(ex.Serial)-18)
END, AggregationLevel
from ExternalCode ex, AggregationLevelConfiguration al
where ex.ProductionOrderId = 4 and
ex.AggregationLevel = al.AggregationLevelConfigurationId
我得到这样的东西:
Serial AggregationLevel
RP4X6BXC1N0RG7 1
RP4X6BXC1N0RG7 1
RP4X6BXC1N0RG7 1
RP4X6BXC1N0RG7 1
RP4X6BXC1N0RG7 1
P5KNX3KBT4997Z 1
P5KNX3KBT4997Z 1
P5KNX3KBT4997Z 1
P5KNX3KBT4997Z 1
P5KNX3KBT4997Z 1
A6GZ9E8ZFA8YMV 1
A6GZ9E8ZFA8YMV 1
A6GZ9E8ZFA8YMV 1
A6GZ9E8ZFA8YMV 1
A6GZ9E8ZFA8YMV 1
EMAMKM4356DHGV 1
EMAMKM4356DHGV 1
EMAMKM4356DHGV 1
EMAMKM4356DHGV 1
EMAMKM4356DHGV 1
WASBFP0EYDM7BM 1
WASBFP0EYDM7BM 1
WASBFP0EYDM7BM 1
WASBFP0EYDM7BM 1
WASBFP0EYDM7BM 1
有什么办法可以避免这种重复?
答案 0 :(得分:2)
添加GROUP BY
来删除重复项:
SELECT Serial, AggregationLevel
FROM (
SELECT
CASE al.NumberEncoding
WHEN 3 THEN RIGHT(ex.Serial,LEN(ex.Serial)-2)
ELSE RIGHT(ex.Serial,LEN(ex.Serial)-18)
END as Serial
, AggregationLevel
FROM ExternalCode ex
JOIN AggregationLevelConfiguration al ON ex.AggregationLevel = al.AggregationLevelConfigurationId
WHERE ex.ProductionOrderId = 4
) nested
GROUP BY Serial, AggregationLevel
答案 1 :(得分:1)
我只会使用DISTINCT
而不是subquery
:
select distinct (case when al.NumberEncoding = 3
then RIGHT(ex.Serial,LEN(ex.Serial)-2)
else RIGHT(ex.Serial,LEN(ex.Serial)-18)
end) as Serial, AggregationLevel
from ExternalCode ex inner join
AggregationLevelConfiguration al
on ex.AggregationLevel = al.AggregationLevelConfigurationId
where ex.ProductionOrderId = 4;
答案 2 :(得分:0)
尝试一下
SELECT * FROM
(
SELECT *, ROW_NUMBER()OVER(PARTITION BY Serial ORDER BY Serial) AS Dup
FROM
(
Select Serial = CASE al.NumberEncoding
WHEN 3 THEN RIGHT(ex.Serial,LEN(ex.Serial)-2)
ELSE RIGHT(ex.Serial,LEN(ex.Serial)-18)
END AS AggregationLevel
FROM ExternalCode ex, AggregationLevelConfiguration al
where ex.ProductionOrderId = 4 and
ex.AggregationLevel = al.AggregationLevelConfigurationId
)dt
)Fnl WHERE Dup=1
答案 3 :(得分:0)
我找到了解决方法:
SELECT Serial, AggregationLevel
FROM (
SELECT
CASE al.NumberEncoding
WHEN 3 THEN RIGHT(ex.Serial,LEN(ex.Serial)-2)
ELSE RIGHT(ex.Serial,LEN(ex.Serial)-18)
END as Serial
, AggregationLevel
FROM ExternalCode ex
JOIN AggregationLevelConfiguration al ON ex.AggregationLevel = al.AggregationLevelConfigurationId
WHERE ex.ProductionOrderId = 4 and al.ProductionOrderId = 4
) nested
我还使用AggregationLevelConfiguration
和ProductionOrderId
添加了约束,而没有使用Group by
。