SQL - How to select a row having a column with max value

前端 未结 9 782
悲&欢浪女
悲&欢浪女 2020-11-29 02:38
date                 value

18/5/2010, 1 pm        40
18/5/2010, 2 pm        20
18/5/2010, 3 pm        60
18/5/2010, 4 pm        30
18/5/2010, 5 pm        60
18/5/20         


        
相关标签:
9条回答
  • 2020-11-29 03:04

    The simplest answer would be

    --Setup a test table called "t1"

    create table t1
    (date datetime,
    value int)
    

    -- Load the data. -- Note: date format different than in the question

    insert into t1
    Select '5/18/2010 13:00',40
    union all
    Select '5/18/2010 14:00',20
    union all
    Select '5/18/2010 15:00',60 
    union all
    Select '5/18/2010 16:00',30 
    union all
    Select '5/18/2010 17:00',60 
    union all
    Select '5/18/2010 18:00',25 
    

    -- find the row with the max qty and min date.

    select *
    from t1
    where value = 
        (select max(value)  from t1)
    and date = 
        (select min(date) 
        from t1
        where value = (select max(value)  from t1))
    

    I know you can do the "TOP 1" answer, but usually your solution gets just complicated enough that you can't use that for some reason.

    0 讨论(0)
  • You can use this function, ORACLE DB

     public string getMaximumSequenceOfUser(string columnName, string tableName, string username)
        {
            string result = "";
            var query = string.Format("Select MAX ({0})from {1} where CREATED_BY = {2}", columnName, tableName, username.ToLower());
    
            OracleConnection conn = new OracleConnection(_context.Database.Connection.ConnectionString);
            OracleCommand cmd = new OracleCommand(query, conn);
            try
            {
                conn.Open();
                OracleDataReader dr = cmd.ExecuteReader();
                dr.Read();
                result = dr[0].ToString();
                dr.Dispose();
            }
            finally
            {
                conn.Close();
            }
            return result;
        }
    
    0 讨论(0)
  • 2020-11-29 03:05

    In Oracle DB:

    create table temp_test1 (id number, value number, description varchar2(20));
    
    insert into temp_test1 values(1, 22, 'qq');
    insert into temp_test1 values(2, 22, 'qq');
    insert into temp_test1 values(3, 22, 'qq');
    insert into temp_test1 values(4, 23, 'qq1');
    insert into temp_test1 values(5, 23, 'qq1');
    insert into temp_test1 values(6, 23, 'qq1');
    
    SELECT MAX(id), value, description FROM temp_test1 GROUP BY value, description;
    
    Result:
        MAX(ID) VALUE DESCRIPTION
        -------------------------
        6         23    qq1
        3         22    qq
    
    0 讨论(0)
提交回复
热议问题