Results 1 to 18 of 18

Thread: [RESOLVED] SELECT MAX from 2 different tables

  1. #1

    Thread Starter
    Member
    Join Date
    Dec 2021
    Posts
    60

    Resolved [RESOLVED] SELECT MAX from 2 different tables

    Hy guys and girls.

    I need to get the MAX value (MyValue) from two tables. The picture gives a better clue about my problem.

    One more thing, table1 contains all the names inside, while table2 doesn't. Another thing, if table2 has the names inside, it is a bigger value than table1 has. That is why I need to get MAX based on these two tables.

    Name:  max.jpg
Views: 96
Size:  23.9 KB

    Thanks

  2. #2
    PowerPoster Zvoni's Avatar
    Join Date
    Sep 2012
    Location
    To the moon and then left
    Posts
    3,847

    Re: SELECT MAX from 2 different tables

    Untested
    Code:
    /* In table2 there seem to be "duplicates" so we're condensing it down 
    to one line per name already grabbing the Max-Value existing in table2*/
    WITH CTE AS (SELECT Name, Max(MyValue) As MaxValue FROM Table2 GROUP BY Name)
    
    SELECT T1.Name, COALESCE(T2.MaxValue, T1.MyValue) AS MaxValue 
    FROM table1 As T1 
    LEFT JOIN CTE As T2 
    ON T2.Name=T1.Name
    WHERE T1.Name='SomeName'
    For 'Spider, above should return 9
    For 'John' above should return 12
    For 'Bruce' above should return 12
    For 'Hero' above should return 13
    Last edited by Zvoni; Tomorrow at 31:69 PM.
    -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ---------------------------------------------------------------------------------
    People call me crazy because i'm jumping out of perfectly fine airplanes.
    ---------------------------------------------------------------------------------
    Code is like a joke: If you have to explain it, it's bad

  3. #3
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,221

    Re: SELECT MAX from 2 different tables

    Code:
    Select XYZ.Name,Max(XYZ.MaxVal) "MaxVal"
        From (Select Name,Max(Value) "MaxVal" From Table1 Group by Name
              Union All
              Select Name,Max(Value) From Table2 Group by Name) as XYZ
        Group by XYZ.Name
    This alternate method should work as well - untested...

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  4. #4
    PowerPoster Zvoni's Avatar
    Join Date
    Sep 2012
    Location
    To the moon and then left
    Posts
    3,847

    Re: SELECT MAX from 2 different tables

    Quote Originally Posted by szlamany;[URL="tel:5600108"
    5600108[/URL]]
    Code:
    Select XYZ.Name,Max(XYZ.MaxVal) "MaxVal"
        From (Select Name,Max(Value) "MaxVal" From Table1 Group by Name
              Union All
              Select Name,Max(Value) From Table2 Group by Name) as XYZ
        Group by XYZ.Name
    This alternate method should work as well - untested...
    leave out those two inner Max-Calls. It‘s unnecessary overhead, since you‘re calling Max on the result of the UNION anyway
    Last edited by Zvoni; Tomorrow at 31:69 PM.
    -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ---------------------------------------------------------------------------------
    People call me crazy because i'm jumping out of perfectly fine airplanes.
    ---------------------------------------------------------------------------------
    Code is like a joke: If you have to explain it, it's bad

  5. #5
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,221

    Re: SELECT MAX from 2 different tables

    Quote Originally Posted by Zvoni View Post
    leave out those two inner Max-Calls. It‘s unnecessary overhead, since you‘re calling Max on the result of the UNION anyway
    If there is an index on NAME, it might make a difference in how each SELECT performs. I would be curious - but not enough to test this out.

    I question the initial table design when a query like this is asked for. Things like the MAX(of "something") should have that "something" be in one "domain" - not two different domains.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  6. #6
    PowerPoster Zvoni's Avatar
    Join Date
    Sep 2012
    Location
    To the moon and then left
    Posts
    3,847

    Re: SELECT MAX from 2 different tables

    Quote Originally Posted by szlamany;[URL="tel:5600115"
    5600115[/URL]]If there is an index on NAME, it might make a difference in how each SELECT performs. I would be curious - but not enough to test this out.

    I question the initial table design when a query like this is asked for. Things like the MAX(of "something") should have that "something" be in one "domain" - not two different domains.
    I know what you mean, but op‘s scenario is something i have to deal with daily, too in the company i work for (doing data analysis on the DB2 database of our ERP). It‘s the reason for my CTE/Left Join approach

    and correct with index comment, but since we don’t know *shrug*
    Last edited by Zvoni; Tomorrow at 31:69 PM.
    -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ---------------------------------------------------------------------------------
    People call me crazy because i'm jumping out of perfectly fine airplanes.
    ---------------------------------------------------------------------------------
    Code is like a joke: If you have to explain it, it's bad

  7. #7

    Thread Starter
    Member
    Join Date
    Dec 2021
    Posts
    60

    Re: SELECT MAX from 2 different tables

    Quote Originally Posted by szlamany View Post
    If there is an index on NAME, it might make a difference in how each SELECT performs. I would be curious - but not enough to test this out.

    I question the initial table design when a query like this is asked for. Things like the MAX(of "something") should have that "something" be in one "domain" - not two different domains.
    I understand my logic could be wrong, but I'll try to explain what am I trying here.

    Table1 is where all the company vehicles are stored. There I have VIN, brand, mileage...
    Table2 is a table of each vehicle service. There could be each vehicle from Table1, but not necessary. Example, when a new (used vehicle) vehicle is registered in Table1, and after some time it comes to service, Table2 doesn't have mileage. In my application, I want that mileage to be calculated automatically, (how many miles there are in between each service), and that is why I need to know the last mileage of the vehicle that is currently imported through the app.

    2 Zvoni, your query works. I've tested it, and tomorrow I'll make a stored procedure with the output parameter. Thanks

    2 szlamany, thank you also. I appreciate any help.

    Edit: now I'm thinking, this could be done with something like SELECT MAX(mileage) from Table2, IF NOT EXIST THEN SELECT Table1.mileage ?
    Last edited by ivansmo; Mar 28th, 2023 at 03:54 PM.

  8. #8
    PowerPoster Zvoni's Avatar
    Join Date
    Sep 2012
    Location
    To the moon and then left
    Posts
    3,847

    Re: SELECT MAX from 2 different tables

    That‘s what COALESCE is doing.
    it returns the first NON-Null result
    Last edited by Zvoni; Tomorrow at 31:69 PM.
    -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ---------------------------------------------------------------------------------
    People call me crazy because i'm jumping out of perfectly fine airplanes.
    ---------------------------------------------------------------------------------
    Code is like a joke: If you have to explain it, it's bad

  9. #9

    Thread Starter
    Member
    Join Date
    Dec 2021
    Posts
    60

    Re: SELECT MAX from 2 different tables

    I'm in trouble of getting value.

    Take a look, please. SQL executes and finds the row, but for some reason, I can't make it to pass the @MaxValue to my app.

    Name:  maxValue.jpg
Views: 65
Size:  27.0 KB

    This is the procedure

    Code:
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER PROCEDURE [dbo].[vozila_max_kilometri]
    
    @VIN varchar(25),
    @MaxValue bigint output
    
    
    AS
    
    BEGIN
    
    WITH CTE AS (SELECT VIN, Max(kilometri) As MaxValue FROM vozila_servisi GROUP BY VIN)
    SELECT vozila.VIN, COALESCE(vozila.kilometri, vozila_servisi.kilometri) AS MaxValue 
    FROM vozila
    LEFT JOIN vozila_servisi
    ON vozila_servisi.VIN=vozila.VIN
    WHERE vozila.VIN=@VIN
    
    /** RETURN; **/
    
    END
    And VB code

    Code:
      con.Open()
                    Dim cmd As New SqlCommand("vozila_max_kilometri", con)
                    With cmd
                        .CommandType = CommandType.StoredProcedure
                        .Parameters.AddWithValue("@VIN", Trim(TXT_VIN.Text))
                        .Parameters.Add("@MaxValue", SqlDbType.BigInt).Direction = ParameterDirection.Output
                        .ExecuteScalar()
    
                        TXT_p_kilometri.Text = cmd.Parameters("@MaxValue").Value.ToString
                    End With
                    con.Close()

  10. #10
    PowerPoster Zvoni's Avatar
    Join Date
    Sep 2012
    Location
    To the moon and then left
    Posts
    3,847

    Re: SELECT MAX from 2 different tables

    This is wrong
    Code:
    WITH CTE AS (SELECT VIN, Max(kilometri) As MaxValue FROM vozila_servisi GROUP BY VIN)
    SELECT vozila.VIN, COALESCE(vozila.kilometri, vozila_servisi.kilometri) AS MaxValue 
    FROM vozila
    LEFT JOIN vozila_servisi
    ON vozila_servisi.VIN=vozila.VIN
    WHERE vozila.VIN=@VIN
    correct (i think)
    WITH CTE AS (SELECT VIN, Max(kilometri) As MaxValue FROM vozila_servisi GROUP BY VIN)
    SELECT vozila.VIN, COALESCE(CTE.MaxValue, vozila.kilometri) AS MaxValue
    FROM vozila
    LEFT JOIN CTE
    ON CTE.VIN=vozila.VIN
    WHERE vozila.VIN=@VIN
    Last edited by Zvoni; Tomorrow at 31:69 PM.
    -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ---------------------------------------------------------------------------------
    People call me crazy because i'm jumping out of perfectly fine airplanes.
    ---------------------------------------------------------------------------------
    Code is like a joke: If you have to explain it, it's bad

  11. #11

    Thread Starter
    Member
    Join Date
    Dec 2021
    Posts
    60

    Re: SELECT MAX from 2 different tables

    Something isn't right here.

    Any chance to join VIN,reg,kilometri from these two tables, and then find MAX value WHERE VIN=''

  12. #12
    PowerPoster Zvoni's Avatar
    Join Date
    Sep 2012
    Location
    To the moon and then left
    Posts
    3,847

    Re: SELECT MAX from 2 different tables

    What is "reg"?

    And i just saw something....
    adjust above to (untested!)
    WITH CTE AS (SELECT VIN, Max(kilometri) As MaxValue FROM vozila_servisi GROUP BY VIN)
    SELECT vozila.VIN, @MaxValue=COALESCE(CTE.MaxValue, vozila.kilometri)
    FROM vozila
    LEFT JOIN CTE
    ON CTE.VIN=vozila.VIN
    WHERE vozila.VIN=@VIN
    Last edited by Zvoni; Tomorrow at 31:69 PM.
    -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ---------------------------------------------------------------------------------
    People call me crazy because i'm jumping out of perfectly fine airplanes.
    ---------------------------------------------------------------------------------
    Code is like a joke: If you have to explain it, it's bad

  13. #13

    Thread Starter
    Member
    Join Date
    Dec 2021
    Posts
    60

    Re: SELECT MAX from 2 different tables

    Reg is registration plate, thank you for helping me

    I'll try it in about one hour. Thanks

  14. #14

    Thread Starter
    Member
    Join Date
    Dec 2021
    Posts
    60

    Re: SELECT MAX from 2 different tables

    Code:
    WITH CTE AS (SELECT VIN, Max(kilometri) As MaxValue FROM vozila_servisi GROUP BY VIN)
    SELECT @MaxValue=COALESCE(vozila.kilometri, vozila_servisi.kilometri)
    FROM vozila
    LEFT JOIN vozila_servisi
    ON vozila_servisi.VIN=vozila.VIN
    WHERE vozila.VIN=@VIN
    It seems this one is working. Tonight I'll do more tests but at first look, it seems that query works.

  15. #15
    PowerPoster Zvoni's Avatar
    Join Date
    Sep 2012
    Location
    To the moon and then left
    Posts
    3,847

    Re: SELECT MAX from 2 different tables

    Quote Originally Posted by ivansmo View Post
    Code:
    WITH CTE AS (SELECT VIN, Max(kilometri) As MaxValue FROM vozila_servisi GROUP BY VIN)
    SELECT @MaxValue=COALESCE(vozila.kilometri, vozila_servisi.kilometri)
    FROM vozila
    LEFT JOIN vozila_servisi
    ON vozila_servisi.VIN=vozila.VIN
    WHERE vozila.VIN=@VIN
    It seems this one is working. Tonight I'll do more tests but at first look, it seems that query works.
    WRONG!
    Look closely at my colored comments!
    In the "main" SELECT-Statement, i don't access table "vozila_servisi" BUT the CTE
    Last edited by Zvoni; Tomorrow at 31:69 PM.
    -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ---------------------------------------------------------------------------------
    People call me crazy because i'm jumping out of perfectly fine airplanes.
    ---------------------------------------------------------------------------------
    Code is like a joke: If you have to explain it, it's bad

  16. #16

    Thread Starter
    Member
    Join Date
    Dec 2021
    Posts
    60

    Re: SELECT MAX from 2 different tables

    Actually the query I've edited doesn't work.

    When I try to ALTER your original code, I get this warning

    Name:  select-warning.jpg
Views: 24
Size:  15.6 KB

  17. #17
    PowerPoster Zvoni's Avatar
    Join Date
    Sep 2012
    Location
    To the moon and then left
    Posts
    3,847

    Re: [RESOLVED] SELECT MAX from 2 different tables

    /* Put my statement without a WHERE clause into a view, then in your SP it‘s a simple select of MaxValue from the view with your WHERE clause */

    alternative is szlamany‘s UNION approach

    EDIT: Just found the explanation: https://stackoverflow.com/questions/...riable-must-no
    The Problem is not the CTE or COALESCE: It's the "additional" Field of VIN in the SELECT
    Remove the VIN from the SELECT
    WITH CTE AS (SELECT VIN, Max(kilometri) As MaxValue FROM vozila_servisi GROUP BY VIN)
    SELECT @MaxValue=COALESCE(CTE.MaxValue, vozila.kilometri)
    FROM vozila
    LEFT JOIN CTE
    ON CTE.VIN=vozila.VIN
    WHERE vozila.VIN=@VIN
    "vozila.VIN," removed
    Last edited by Zvoni; Mar 30th, 2023 at 01:44 AM.
    Last edited by Zvoni; Tomorrow at 31:69 PM.
    -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ---------------------------------------------------------------------------------
    People call me crazy because i'm jumping out of perfectly fine airplanes.
    ---------------------------------------------------------------------------------
    Code is like a joke: If you have to explain it, it's bad

  18. #18

    Thread Starter
    Member
    Join Date
    Dec 2021
    Posts
    60

    Re: [RESOLVED] SELECT MAX from 2 different tables

    Quote Originally Posted by Zvoni View Post
    /* Put my statement without a WHERE clause into a view, then in your SP it‘s a simple select of MaxValue from the view with your WHERE clause */

    alternative is szlamany‘s UNION approach

    EDIT: Just found the explanation: https://stackoverflow.com/questions/...riable-must-no
    The Problem is not the CTE or COALESCE: It's the "additional" Field of VIN in the SELECT
    Remove the VIN from the SELECT

    "vozila.VIN," removed
    Yap, yesterday I removed vozila.VIN and today I tested query carefully. It is exactly what I want it to do

    Thank you very much

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width