Get column name which has the max value in a row sql

前端 未结 4 839
孤城傲影
孤城傲影 2021-01-20 22:47

I have a a table in my database where I store categories for newsarticles and each time a user reads an article it increments the value in the associated column. Like this:<

4条回答
  •  执念已碎
    2021-01-20 23:16

    This will get you started with the concept of grabbing the highest value from multiple columns on a single row (modify for your specific tables - I created a fake one).

    create table fake 
    (
      id int Primary Key,
      col1 int,
      col2 int,
      col3 int,
      col4 int 
    )
    insert into fake values (1, 5, 9, 27, 10)
    insert into fake values (2, 3, 5, 1, 20)
    insert into fake values (3, 89, 9, 27, 6)
    insert into fake values (4, 17, 40, 1, 20)
    
    SELECT *,(SELECT Max(v) 
    FROM (VALUES (col1), (col2), (col3), (col4) ) AS value(v))
    FROM fake
    

提交回复
热议问题