选择(选择union all select)错误

时间:2015-05-18 12:59:59

标签: sql sql-server

此查询有什么问题:

SELECT AVG(price) as AVG_price FROM 
(
 (SELECT price FROM PC, Product WHERE maker = 'A' AND Product.model = PC.model)
  UNION ALL
 (SELECT price FROM Laptop, Product WHERE maker = 'A' AND Product.model = Laptop.model)
)

它出现以下错误:

  

')'

附近的语法不正确

5 个答案:

答案 0 :(得分:3)

试试这个..

SELECT AVG(d.price) as AVG_price FROM 
(
 SELECT price FROM PC, Product WHERE maker = 'A' AND Product.model = PC.model
  UNION ALL
 SELECT price FROM Laptop, Product WHERE maker = 'A' AND Product.model = Laptop.model
) as d

答案 1 :(得分:2)

将派生表作为别名并转换为SQL-92 ANSI标准。

SELECT AVG(price) as AVG_price FROM 
(
 SELECT price FROM PC INNER JOIN Product on Product.model = PC.model
 WHERE maker = 'A' 
  UNION ALL
 SELECT price FROM Laptop  INNER JOIN Product on Product.model = Laptop.model
 WHERE maker = 'A'
) B

答案 2 :(得分:2)

使用现代风格JOIN s:

SELECT AVG(price)
FROM 
(
 SELECT price
 FROM PC JOIN Product ON Product.model = PC.model
 WHERE maker = 'A'

 UNION ALL

 SELECT price
 FROM Laptop JOIN Product  ON Product.model = Laptop.model
 WHERE maker = 'A'
) as dt

答案 3 :(得分:1)

请尝试这种语法。

SELECT AVG(price) as AVG_price FROM 
(
  (SELECT price FROM PC, Product WHERE maker = 'A' AND Product.model =  PC.model)
  UNION ALL
  (SELECT price FROM Laptop, Product WHERE maker = 'A' AND Product.model = Laptop.model)
) AS ALIAS_NAME

我在查询结尾处添加了ALIAS_NAME。这可以解决你的问题。

答案 4 :(得分:1)

我认为您需要为内联表提供别名

SELECT AVG(price) as AVG_price FROM 
(
     (SELECT price FROM PC, Product WHERE maker = 'A' AND Product.model = PC.model)
      UNION ALL
     (SELECT price FROM Laptop, Product WHERE maker = 'A' AND Product.model = Laptop.model)
) tableAlias

应该做的伎俩