从两个表中选择最大值,最小值

时间:2011-10-24 14:18:26

标签: sql database select union

我有两张桌子。不同之处在于存档是一个表而另一个存放当前记录。这些是记录公司销售额的表格。在这两个领域我们都有:id,名称,销售价格。我需要从两个表中选择给定名称的最高价和最低价。我尝试使用查询:

select name, max (price_of_sale), min (price_of_sale)
from wapzby
union
select name, max (price_of_sale), min (price_of_sale)
from wpzby
order by name

但是这样的查询给了我两条记录 - 一张当前表,一张表档案。我想立即从两个表中选择最小和最大价格的名称。我如何获得此查询?

4 个答案:

答案 0 :(得分:25)

这是两个选项(符合MSSql)

注意:UNION ALL将组合这些集合而不会消除重复。这比UNION简单得多。

SELECT Name, MAX(Price_Of_Sale) as MaxPrice, MIN(Price_Of_Sale) as MinPrice
FROM
(
    SELECT Name, Price_Of_Sale
    FROM wapzby
    UNION ALL
    SELECT Name, Price_Of_Sale
    FROM wpzby
) as subQuery
GROUP BY Name
ORDER BY Name

这个在计算组合之前计算每个表的最大值和最小值 - 以这种方式执行它可能更有效。

SELECT Name, MAX(MaxPrice) as MaxPrice, MIN(MinPrice) as MinPrice
FROM
(
    SELECT Name, MAX(Price_Of_Sale) as MaxPrice, MIN(Price_Of_Sale) as MinPrice
    FROM wapzby
    GROUP BY Name
    UNION ALL
    SELECT Name, MAX(Price_Of_Sale) as MaxPrice, MIN(Price_Of_Sale) as MinPrice
    FROM wpzby
    GROUP BY Name
) as subQuery
GROUP BY Name
ORDER BY Name

答案 1 :(得分:7)

在SQL Server中,您可以使用subquery

SELECT  [name],
        MAX([price_of_sale]) AS [MAX price_of_sale],
        MIN([price_of_sale]) AS [MIN price_of_sale]
FROM (
    SELECT  [name],
            [price_of_sale]
    FROM    [dbo].[wapzby]
    UNION
    SELECT  [name],
            [price_of_sale]
    FROM    [dbo].[wpzby]
) u
GROUP BY [name]
ORDER BY [name]

答案 2 :(得分:2)

这更像你想要的吗?

SELECT 
    a.name,
    MAX (a.price_of_sale), 
    MIN (a.price_of_sale) ,  
    b.name, 
    MAX (b.price_of_sale), 
    MIN (b.price_of_sale) 
FROM 
    wapzby a, 
    wpzby b
ORDER BY 
    a.name 

它未经测试但应该在一行中返回所有记录,而不需要联合

答案 3 :(得分:1)

SELECT MAX(value) FROM tabl1 UNION SELECT MAX(value) FROM tabl2;
SELECT MIN(value) FROM tabl1 UNION SELECT MIN(value) FROM tabl2;