3个表sto_Product,sto_ProductXCategory和sto_Category
目前它会产生重复的产品,因为某些产品在sto_ProductXCategory中有重复(具有不同的CategoryId)。
这个SQL语句是一个更大的存储过程的一部分,所以我试图保持它类似。
这是我正在努力修复的声明
DECLARE @Sortorder int =6;
with product as
(
select distinct p.*
from sto_Product p
inner join sto_ProductXCategory px on(p.bvin = px.productid)
where p.parentID = ''
and p.Status = 1
and p.siteprice >=0
and p.siteprice <= 2147483647
and (
(p.manufacturerid = '8036ab2c-641e-487b-a577-76c09c5c3cc9'
)
)
),
AllProducts AS
(
SELECT
RowNum =
CASE
WHEN @Sortorder = 0
THEN ROW_NUMBER() OVER (ORDER BY px.SortOrder)
WHEN @Sortorder = 1
THEN ROW_NUMBER() OVER (ORDER BY px.SortOrder)
WHEN @Sortorder = 2
THEN ROW_NUMBER() OVER (ORDER BY ProductName)
WHEN @Sortorder = 3
THEN ROW_NUMBER() OVER (ORDER BY SitePrice)
WHEN @Sortorder = 4
THEN ROW_NUMBER() OVER (ORDER BY SitePrice DESC)
WHEN @Sortorder = 6
THEN ROW_NUMBER() OVER (ORDER BY ProductName DESC)
ELSE ROW_NUMBER() OVER (ORDER BY px.SortOrder)
END,
p.*
from product p
inner join sto_ProductXCategory px on(p.bvin = px.productid)
)
SELECT AllProducts.RowNum,*,
(SELECT COUNT(*) FROM AllProducts) As TotalRowCount
FROM AllProducts
WHERE RowNum BETWEEN (1) and (12 )
ORDER BY AllProducts.RowNum
sto_Product
sto_Category
sto_ProductXCategory
提前致谢
答案 0 :(得分:1)
你说过
...目前它产生了重复的产品,因为某些产品在sto_ProductXCategory中有重复(具有不同的CategoryId)。
但你还没有说出你想要发生什么。
出于我的目的,我假设你只想要每个产品一行,忽略sto_ProductXCategory中出现的CategoryID的不同值
在AllProducts中你有:
from product p inner join sto_ProductXCategory px on(p.bvin = px.productid)
这需要更改为过滤sto_ProductXCategory中您不希望输出数据集中的重复行;
from product p join (
select productid, min(categoryid) as Category
from sto_ProductXCategory
group by productid
) x on p.bvin = x.productid
join sto_ProductXCategory px on p.bvin = px.Productid and x.Category = px.CategoryID
怎么样?