Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select max, min values from two tables

I have two tables. Differ in that an archive is a table and the other holds the current record. These are the tables recording sales in the company. In both we have among other fields: id, name, price of sale. I need to select from both tables, the highest and lowest price for a given name. I tried to do with the query:

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

but such an inquiry draws me two records - one of the current table, one table archival. I want to chose a name for the smallest and the largest price immediately from both tables. How do I get this query?

like image 755
BKl Avatar asked Oct 24 '11 14:10

BKl


4 Answers

Here's two options (MSSql compliant)

Note: UNION ALL will combine the sets without eliminating duplicates. That's a much simpler behavior than 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

This one figures out the max and min from each table before combining the set - it may be more performant to do it this way.

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
like image 191
Amy B Avatar answered Sep 22 '22 02:09

Amy B


In SQL Server you could use a 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]
like image 22
Tom Hunter Avatar answered Sep 23 '22 02:09

Tom Hunter


Is this more like what you want?

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 

It's untested but should return all your records on one row without the need for a union

like image 29
Purplegoldfish Avatar answered Sep 24 '22 02:09

Purplegoldfish


SELECT MAX(value) FROM tabl1 UNION SELECT MAX(value) FROM tabl2;
SELECT MIN(value) FROM tabl1 UNION SELECT MIN(value) FROM tabl2;
like image 30
Karim Elshaweish Avatar answered Sep 22 '22 02:09

Karim Elshaweish