【发布时间】:2013-09-28 19:31:35
【问题描述】:
我的第一个版本的问题令人困惑,我需要制作更小的块。 如果用户可以过滤网站中的产品,那么一个产品应该只在列表中出现一次。 由于加入此代码给了我两个相同的产品,我该如何解决? 我想我需要一个不使用 distinct 的解决方案,因为它会在以后让我头疼。
来自 AW2012 的代码:
declare @safetystocklevel int
set @safetystocklevel = 1000
declare @status int
set @status = 2
select * from Production.Product p
inner join Purchasing.ProductVendor pv on p.ProductID = pv.ProductID
inner join Purchasing.Vendor v on v.BusinessEntityID = pv.BusinessEntityID
inner join Production.ProductDocument pd on p.ProductID = pd.ProductID
inner join Production.Document d on d.DocumentNode = pd.DocumentNode
WHERE
(@safetystocklevel = '' or p.SafetyStockLevel = @safetystocklevel)
and (@status = '' or d.Status = @status)
输出:
产品 ID 名称
506反光板
506反光板
编辑:
谢谢,我现在使用 Group by 来获取不同的行。 是的,也许使用 group by 对我有用,我现在要做一些测试.....
再见
我希望所有产品都是可搜索的,所以我想我需要左外连接来实现这一点。 当我添加动态订单时遇到麻烦,会添加更多行。 可能是因为我必须将 poh.Status 添加到 group by。 product 表有 504 行,此查询返回 776 行。 (我已经删除了 WHERE 中的过滤,因为它现在不有趣了,我现在加入其他表只是为了获得更多的行来玩)
代码:
declare @sortType nvarchar(50)
set @sortType = 'Status'
select p.ProductID,
CASE WHEN @sortType = 'Status' THEN poh.Status END as Status,
CASE WHEN @sortType = 'ProductId' THEN p.ProductID END as ProductId
from Production.Product p
left outer join Purchasing.PurchaseOrderDetail pod on p.ProductID = pod.ProductID
left outer join Purchasing.PurchaseOrderHeader poh on poh.PurchaseOrderID = pod.PurchaseOrderID
left outer join Production.ProductDocument ppd on ppd.ProductID = p.ProductID
left outer join Production.Document pd on pd.DocumentNode = ppd.DocumentNode
group by p.ProductID, poh.Status
ORDER BY
CASE WHEN @sortType = 'Status' THEN poh.Status END ASC,
CASE WHEN @sortType = 'ProductId' THEN p.ProductID END ASC
【问题讨论】:
-
你能澄清一下你的问题吗?目前还不清楚你想要实现什么。您能否展示一个(可能是手工制作的)表格来展示您期望获得的(部分)数据?
-
嗨,我已经更新了问题
-
@CliffSmith,我想既然您使用的是 distinct,那么其中一个表是 1-n,在这种情况下是哪一个?我的意思是,是什么导致结果集有多个产品行,而您只想要一个?
-
问题更新了
-
包括所有字段并检查导致重复的原因。而且,如果您要删除重复项,则包括导致两行的条件.....或在选择查询中包括该列。
标签: sql-server tsql sql-server-2005