添加PriceZoneID列时代码不起作用

时间:2018-07-17 16:46:04

标签: sql sql-server

我正在尝试从数据库中获得部门的唯一列表,以及部门的价格区ID号。

有人知道此代码为什么起作用(获取部门名称的唯一列表),但下面的后续代码却无效(唯一的区别是它添加了ps.PriceZoneID-PriceZoneID是PriceZone表中的一列)。

有效的代码:

Select  
    distinct (es.DepartmentName)
FROM AggregatedSalesHistory as ASH 
JOIN v_EnterpriseStructure as es on es.ProductSID = ash.ProductSID
JOIN PriceZone as ps on es.ProductSID = ash.ProductSID

无效的代码。

Select
    ps.PriceZoneID,
    distinct (es.DepartmentName)
FROM AggregatedSalesHistory as ASH 
JOIN v_EnterpriseStructure as es on es.ProductSID = ash.ProductSID
JOIN PriceZone as ps on es.ProductSID = ash.ProductSID

先谢谢了。

1 个答案:

答案 0 :(得分:3)

Distinct适用于所有列或表达式,但不起作用:

所以,应该是:

SELECT DISTINCT ps.PriceZoneID, es.DepartmentName
FROM AggregatedSalesHistory as ASH JOIN 
     v_EnterpriseStructure as es 
     ON es.ProductSID = ash.ProductSID JOIN 
     PriceZone as ps 
     ON es.ProductSID = ash.ProductSID;

或者您可能需要:

SELECT TOP (1) WITH TIES ps.PriceZoneID, es.DepartmentName
FROM AggregatedSalesHistory as ASH JOIN  
     v_EnterpriseStructure as es 
     ON es.ProductSID = ash.ProductSID JOIN 
     PriceZone as ps 
     ON es.ProductSID = ash.ProductSID
ORDER BY ROW_NUMBER() OVER (PARTITION BY es.DepartmentName ORDER BY ps.PriceZoneID);