从聚合函数中排除一些记录
Posted
技术标签:
【中文标题】从聚合函数中排除一些记录【英文标题】:Exclude some records from aggregate function 【发布时间】:2013-07-05 13:24:17 【问题描述】:拥有这段 SQL 代码:
MIN([Price]) OVER (PARTITION BY [Brand], [Article]) AS MinPrice,
问题:如何从MIN()
中排除一些记录,其中 a.e. [Supplier] != 10
?
【问题讨论】:
【参考方案1】:将WHERE [Supplier] != 10
添加到您的查询中。
【讨论】:
我说的是查询。SELECT MIN([Price]) OVER (PARTITION BY [Brand], [Article]) AS MinPrice FROM Table WHERE [Supplier] != 10
又出问题了,最好把我的代码显示出来:SELECT TOP 1000 p.* FROM (SELECT p.*, MIN([SDA_COST]) OVER (PARTITION BY [SDA_BRA_ID], [SDA_ART_ID]) AS MinPrice, MIN([SDA_COST]) OVER (PARTITION BY [SDA_BRA_ID], [SDA_ART_ID]) AS MinConcPrice FROM [autoparts_portal].[dbo].[CI_SUP_DATA] p ) p where [SDA_SUP_ID] = 10 AND ([SDA_COST] < 0.98 * MinConcPrice OR [SDA_COST] != MinPrice); GO
我只需要从每个组的 MIN 函数中排除指定供应商的记录或执行任何其他检查逻辑。
使用此代码:SELECT TOP 1000 p.* FROM (SELECT p.*, MIN([Price]) OVER (PARTITION BY [Brand], [Article]) AS MinPrice, (SELECT MIN([Price]) OVER (PARTITION BY [Brand], [Article]) FROM [autoparts_portal].[dbo].[CI_SUP_DATA] WHERE [Supplier] != 10) AS MinConcPrice FROM [autoparts_portal].[dbo].[CI_SUP_DATA] p ) p where [SDA_SUP_ID] = 10 AND ([Price] < 0.98 * MinConcPrice OR [Price] > MinPrice); GO
出现错误“嵌套查询返回多个值”
子查询 (SELECT MIN([Price]) OVER (PARTITION BY [Brand], [Article]) FROM [autoparts_portal].[dbo].[CI_SUP_DATA] WHERE [Supplier] != 10)
将返回不止一行。这就是它所抱怨的,我怀疑。包含在 SELECT 子句(与 FROM 子句相反)中的子查询必须只返回一个值。以上是关于从聚合函数中排除一些记录的主要内容,如果未能解决你的问题,请参考以下文章