SQL - 使用UNION时出错

时间:2016-06-26 18:09:15

标签: sql sql-server union

这是我的疑问:

Select top 1 ProductName, UnitPrice from Products
order by UnitPrice desc

UNION

Select top 1 ProductName, UnitPrice from Products
Where UnitPrice > 0
order by UnitPrice asc

我想在一张桌子上展示最贵和最便宜的产品。这就是我使用UNION加入这两个查询的原因。不幸的是我收到了错误

  

关键字' UNION'

附近的语法不正确

这就是为什么我要求你的帮助 - 我的查询有什么问题?

3 个答案:

答案 0 :(得分:2)

;WITH X AS 
  (
    Select top 1 ProductName, UnitPrice from Products
    order by UnitPrice desc
  ), 
 Y AS 
  (
    Select top 1 ProductName, UnitPrice from Products
    Where UnitPrice > 0
    order by UnitPrice asc 
)
SELECT ProductName, UnitPrice FROM X
UNION ALL
SELECT ProductName, UnitPrice FROM Y

答案 1 :(得分:2)

作为子选择

SELECT *
FROM
    (
    SELECT *
       ,MinPriceRowNum = ROW_NUMBER() OVER (ORDER BY Start_Dt)
       ,MaxPriceRowNum = ROW_NUMBER() OVER (ORDER BY Start_Dt DESC)
       ,MinPriceRank = DENSE_RANK() OVER (ORDER BY Start_Dt)
       ,MaxPriceRank = DENSE_RANK() OVER (ORDER BY Start_Dt DESC)
    FROM    
       #Table
    ) t
WHERE
    MinPriceRowNum = 1
    OR MaxPriceRowNum = 1

AS Common Table Expression cte

;WITH cte AS (
    SELECT *
       ,MinPriceRowNum = ROW_NUMBER() OVER (ORDER BY UnitPrice)
       ,MaxPriceRowNum = ROW_NUMBER() OVER (ORDER BY UnitPriceDESC)
       ,MinPriceRank = DENSE_RANK() OVER (ORDER BY UnitPrice)
       ,MaxPriceRank = DENSE_RANK() OVER (ORDER BY UnitPriceDESC)
    FROM    
       TableName
)

SELECT *
FROM
    cte
WHERE
    MinPriceRowNum = 1
    OR MaxPriceRowNum = 1

如果您想查看max和min的所有关系切换到MinPriceRank = 1 OR MaxPriceRank = 1。如果只有一行需要保留RowNum列。

答案 2 :(得分:1)

您可以使用这样的圆括号:

(Select top 1 ProductName, UnitPrice from Products order by UnitPrice desc)
UNION
(Select top 1 ProductName, UnitPrice from Products Where UnitPrice > 0 order by UnitPrice asc)

干杯!