SQl有子句Min方法无效

时间:2013-08-14 15:55:33

标签: sql sql-server

使用SQL Server Manager 2008 快速简单的, 得到了这个问题:

SELECT sizecode as smaller
from safestore.dbo.SpaceMan_EvoPrices
WHERE SiteId = 'derp' AND Publish = 'Y' AND SizeCode = 'herp'
HAVING PhysicalSize < MIN(PhysicalSize)

在HAVING子句中无效,因为它不包含在聚合函数或GROUP BY子句中。 添加了一个组但不确定如何将它添加到group by子句才有效。 你可以告诉我,直到现在我都没用过。

有什么想法吗?

编辑:

这个查询是我试图缩短的原始查询,因为它看起来很头疼:

SELECT TOP 1 (SELECT TOP 1 Sizecode 
FROM [safestore].[dbo].[SpaceMan_EvoPrices]
WHERE PhysicalSize < (SELECT TOP 1 PhysicalSize FROM [safestore].[dbo].   [SpaceMan_EvoPrices] WHERE SiteId = 'derp' AND Publish = 'Y' AND SizeCode =   'herp')
AND SiteId = 'derp'
ORDER BY PhysicalSize DESC) AS Smaller,
(SELECT TOP 1 Sizecode 
FROM [safestore].[dbo].[SpaceMan_EvoPrices]
WHERE PhysicalSize > (SELECT TOP 1 PhysicalSize FROM [safestore].[dbo].  [SpaceMan_EvoPrices] WHERE SiteId = 'derp' AND Publish = 'Y' AND SizeCode =   'herp')
AND SiteId = 'derp'
ORDER BY PhysicalSize) AS Larger
FROM [safestore].[dbo].[SpaceMan_EvoPrices]

2 个答案:

答案 0 :(得分:1)

就您的查询而言。它应该是这样的

SELECT sizecode as smaller,PhysicalSize 
from safestore.dbo.SpaceMan_EvoPrices
WHERE SiteId = '080P2DDK120820090001' AND Publish = 'Y' AND SizeCode = '50SA'
Group by PhysicalSize 
HAVING PhysicalSize < MIN(PhysicalSize)  --not sure y this line

答案 1 :(得分:1)

试试这个 -

;WITH cte AS (
    SELECT PhysicalSize, Publish, SizeCode
    FROM dbo.SpaceMan_EvoPrices
    WHERE SiteId = 'derp'
)
SELECT
      Smaller = (
        SELECT TOP 1 Sizecode
        FROM cte
        WHERE PhysicalSize < t.PhysicalSize
        ORDER BY PhysicalSize DESC
      )
    , Larger = (
        SELECT TOP 1 Sizecode
        FROM cte
        WHERE PhysicalSize > t.PhysicalSize
        ORDER BY PhysicalSize
      )
FROM (
    SELECT TOP 1 PhysicalSize
    FROM cte
    WHERE Publish = 'Y'
        AND SizeCode = 'herp'
) t