繁体   English   中英

SQL "all in" group by

[英]SQL "all in" group by

我在使用某些 sql 语句时遇到了麻烦。

我有一张这样的表:

桌子

我找不到任何 SQL 形式来做到这一点,但我想要这样的东西:

SELECT 
   Col1, 
   CASE WHEN all(Col2 in ('A','B','C') THEN "auto"
        ELSE distinct Col2 not in ('A','B','C')        as Col2
FROM mytable
GROUP BY Col1

显然查询不是有效的 SQL,所以我在这里解释我想要的:如果组中的所有寄存器都是 A、B 或 CI,则希望列值为“AUTO”,另一方面,如果有任何列值不同比 A、B 或 CI 想要选择它。

所以结果应该是:

Col1   Col2
1      AUTO
2      R

您可以使用聚合:

select
    col1,
    coalesce(max(case when Col2 not in ('A', 'B', 'C') then Col2 end), 'AUTO') Col2
from mytable 
group by col1

如果给定Col1Col2所有值都属于A/B/C ,则max(case when Col2 not in ('A', 'B', 'C') then Col2 end)返回null ,外部合并变为到'AUTO' 否则,返回A/B/C以外的最大值。

查看您的示例似乎您只需要包含所有 3 个值 ('A','B','C') 的 col1,而对于其他人,则不需要 ('A','B','C')

select  t.col1 , t.check
from  (
  select  col1, 'AUTO' check
  from mytable 
  group by  col1 
  HAVING count(distinct col2)=3 
) t
inner join  mytable m on t.col1 = m.col1 and m.col2 in ('A','B','C')
UNION 

select col1, col2 
from mytable 
where col2 not in  ('A','B','C')

试试这个代码:

-- drop table #t ;
create table #t (col1 INT, col2 nvarchar(32));
insert into #t values (1,'A'),(1,'B'),(1,'C'),(2,'A'),(2,'B'),(2,'R')
-- select * from #t

select 
    col1,
    case 
        when SUM(case when col2 in ('A','B','C') then 1 else 0 end) = COUNT(1)
        then 'auto'
        else MAX(case when col2 in ('A','B','C') then '' else col2 end)
    end col2_groupped
from
    #t
group by
    col1

您首先需要非AUTO案例列表,然后是不在第一个列表中的AUTO列表:

with datas (col1, col2) as (
  values
  (1, 'A'),
  (1, 'B'),
  (1, 'C'),
  (2, 'A'),
  (2, 'B'),
  (2, 'R')
),
not_auto as (
  select col1, col2 from datas where col2 not in ('A', 'B', 'C')
)
select col1, 'AUTO' as col2 from datas
  where col2 in ('A', 'B', 'C')
        and not exists(select 0 from not_auto where not_auto.col1 = datas.col1) group by col1
union all
select * from not_auto
order by col1, col2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM