在SQL中汇总行

问题描述

我想在“ U”上选择“ Y”或“ N”,只要有两个具有相同ID的行。但是,当id仅有一行时,我想保留“ U”。任何人都可以展示一种汇总下表的有效方法:

enter image description here

变成这样:

enter image description here

我尝试了MAX函数,但它仅按字母顺序保留值,并且'U'恰好位于'Y'和'N'的中间,因此MAX函数无法按我的预期工作。

很高兴听到您的想法。

解决方法

您可以使用窗口功能:

library(ggpubr)
#> Loading required package: ggplot2
ggboxplot(
   mtcars,x = "am",y = c("disp","hp"),combine = TRUE,color = c("#0073C2FF","#EFC000FF","#0073C2FF","#EFC000FF"),title = NULL,ylab = ''
)


或者,我们可以将字符串转换为数字,选择首选值,然后转换回原始字符串:

select id,ind
from (
    select t.*,row_number() over(
        partition by id 
        order by case ind
            when 'Y' then 1
            when 'N' then 2
            when 'U' then 3
            else 4           -- is this possible?
        end
    ) rn
    from mytable t
) t
where rn = 1
,

另一种方法是聚合:

select id,coalesce(max(case when ind = 'Y' then ind end),max(case when ind = 'N' then ind end),max(case when ind = 'U' then ind end)
               )
from t
group by id;

这只是运行逻辑:

  • 如果有'Y',请返回'Y'
  • 否则,如果有'N',请返回'N'
  • 否则,如果有'U',请返回'U'
,

假设您必须从“ U”,“ Y”和“ N”中进行选择,并且最多显示2种,则可以将 Max 函数与group by一起使用。

SELECT id,MAX(Ind)
FROM mytable
GROUP BY id
order by id

此查询将适用于大多数数据库。 使用以上内容时要小心,尽管其简单而又小巧,但有很多限制。在投入生产之前,请对其进行彻底的测试,并考虑所有测试用例。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...