1

使用 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 但不确定如何将其添加到 group by 子句中才有效。正如你所知道的,我从来没有使用过Having。

有什么想法吗?

编辑:

这个查询是我试图缩短的原始查询,因为它让人头疼:

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]
4

2 回答 2

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
于 2013-08-14T16:01:38.740 回答
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
于 2013-08-15T05:52:34.197 回答