在一个 select 内生成多个相同 case 的别名

Generate several aliases in the same case within a select

我正在 SQL 中生成查询,我需要为 selectcase 中的每个条件生成三列,但我只知道如何通过用相同的时间创建三个案例。 我还需要别名相同,但在生成相同的别名时,前缀“_1”和“_2”会重复添加多次。

这是query:

select
    distinct Layout,
    case when Layout = 'Midd' then 'mid' end as FIR,
    case when Layout = 'Midd' then 'mid' end as SEC,
    case when Layout = 'Midd' then 'mid' end as THI,
    case when Layout = 'Ser' then null end as FIR,
    case when Layout = 'Ser' then null end as SEC,
    case when Layout = 'Ser' then null end as THI,
    case when Layout = 'Cloud' then ser end as FIR,
    case when Layout = 'Cloud' then mid end as SEC,
    case when Layout = 'Cloud' then clo end as THI
from SUMMARY

这是我得到的:

Layout  FIR  SEC  THI  FIR_1  SEC_1  THI_1  FIR_2  SEC_2  THI_2     
Midd    mid  mid  mid  null   null   null   null   null   null
Ser     null null null null   null   null   null   null   null
Cloud   null null null null   null   null   dataS  dataM  dataC

这就是我想要实现的:

Layout  FIR    SEC    THI   
Midd    mid    mid    mid  
Ser     null   null   null 
Cloud   dataS  dataM  dataC

这是我想得到的查询,但我不知道如何让它工作:

    select
        distinct Layout,
        case when Layout = 'Midd' then 'mid' end as FIR, SEC, THI,
        case when Layout = 'Ser' then null end as FIR, SEC, THI,
        case when Layout = 'Cloud' then ser as FIR and mid as SEC and clo as THI
    from SUMMARY

看到这个fiddle:

https://dbfiddle.uk/?rdbms=mysql_5.5&fiddle=48e63abb462890293f2fa7b54860bf5d

另外,您应该包含一个 fiddle 以及一些示例数据和您的特定数据库。这将使人们更容易回答你。例如,您在查询中引用了 I.ser、I.mid 和 I.clo,但我真的不知道它们会包含什么,或者如何针对任何内容编写查询就像我在这里别名一样。相反,为了演示的目的,我使用了静态值。

您需要制作单独的 CASE 语句,一个用于您打算生成的每一列,然后为每个添加多个 WHEN 条件:

select
    distinct Layout,
    case when Layout = 'Midd'  then  'mid'
         when Layout = 'Ser'   then   null
         when Layout = 'Cloud' then   I.ser end as FIR,
    case when Layout = 'Midd'  then  'mid'
         when Layout = 'Cloud' then   I.mid
         when Layout = 'Ser'   then   null end as SEC,
    case when Layout = 'Midd'  then  'mid'
         when Layout = 'Ser'   then   null
         when Layout = 'Cloud' then   I.clo end as THI
from SUMMARY