SQL - 使用 UNION 时出错

SQL - error when using 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

我想将最贵和最便宜的产品集中展示 table。这就是我使用 UNION 连接两个查询的原因。不幸的是我得到一个错误

Incorrect syntax near the keyword '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)

干杯!

;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

作为替补 Select

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

A​​S 通用 Table 表达式 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

如果您想查看最大值和最小值的所有关系,请切换到 MinPriceRank = 1 OR MaxPriceRank = 1。如果只需要 1 行,请保留 RowNum 列。