【问题标题】:Select Max and Select other column选择最大值并选择其他列
【发布时间】:2014-09-15 01:24:04
【问题描述】:

我正在尝试从一列中获取 max + 1 值,并从另一列中获取所有值。但是,我的查询没有给出任何结果。

例如,

 SectionItemID   SectionItem
 1                    blue
 2                    red

查询应该返回

SectionItemID    SectionItem
3                    blue
                     red

这就是我所拥有的

SELECT SectionItem,MAX(SectionItemID) + 1 AS SectionItemID FROM Core.SectionItem_Lkup 

【问题讨论】:

标签: mysql sql select max


【解决方案1】:
SELECT SectionItem,
       (select MAX(SectionItemID)+1 FROM Core.SectionItem_Lkup) AS SectionItemID
FROM Core.SectionItem_Lkup

【讨论】:

  • 谢谢你,这就是我要找的东西
【解决方案2】:

每当您GROUP BY 时,您应该聚合涉及的其他列。

  • Mysql 允许在其他列上省略聚合
  • MsSQL 没有,因为没有聚合的列的结果未定义。

聚合其他列的最佳方式是。对于您的情况,您可以使用group_concat

  SELECT MAX(SectionItemID)+1, Group_concat(SectionItem) FROM tbl 

注意:查询不包含任何Group By,因为您不想在SectionItemId 或SectionItem 上分组。省略 Group By 并使用聚合函数将在整个表上使用它们。

输出:

MAX(SECTIONITEMID)+1    GROUP_CONCAT(SECTIONITEM)
3                     blue,red

http://sqlfiddle.com/#!2/353bf3/6

【讨论】:

    【解决方案3】:
    select case when t2.SectionItem = 'blue' 
        then cast(max(t1.SectionItemID) + 1 as varchar(1))
        else '' end 
    as SectionItemID
    , t2.SectionItem
    from Core.SectionItem_Lkup t1
    full outer join Core.SectionItem_Lkup t2 on 1 = 1
    group by t2.SectionItem
    order by 
    case when t2.SectionItem = 'blue' 
        then cast(max(t1.SectionItemID) + 1 as varchar(1))
        else '' end 
    desc
    

    【讨论】:

    • 这将完全返回您在此处显示的输出。
    猜你喜欢
    • 1970-01-01
    • 2014-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 2022-11-23
    相关资源
    最近更新 更多