根据原始列之一中的值对一些新值进行分组

Posted

技术标签:

【中文标题】根据原始列之一中的值对一些新值进行分组【英文标题】:Unpivot some data grouping the new values based on the value in one of the original columns 【发布时间】:2019-10-24 14:20:53 【问题描述】:

在让 Unpivot 完全按照我的意愿行事时遇到了一些麻烦,不确定是否可以在没有其他联接或联合的情况下(如果可能的话,我想避免)任何帮助将不胜感激。 :)

select *
  from (select "Not Executed" + "Pass" + "Fail" + "Blocked" As "Total",
               "Pass" + "Fail" + "Blocked" As "Executed",
               "Pass",
               "Fail",
               "Blocked",
               "Not Executed",
               Priority        
          from (select TRS.NAME AS Status, TPS.Name as Priority
                  from TEST_RESULT TR
                  join (Select ID, NAME
                         from RESULT_STATUS
                        where "GROUP" = 'TEST_RESULT_STATUS') TRS
                    on TR.TEST_RESULT_STATUS_ID = TRS.ID
                  join TEST_RUN TRN
                    on TR.TEST_RUN_ID = TRN.ID
                  join TEST_CASE TC
                    on TC.ID = TR.TEST_CASE_ID
                  join (Select ID, NAME
                         from RESULT_STATUS
                        where "GROUP" = 'TEST_CASE_PRIORITY') TPS
                    on TC.PRIORITY_ID = TPS.ID
                --Add your test cycles that you want to report on here
                 where TRN.KEY IN ('PSD-C3')

                ) pivot(count(Status) for Status in('Not Executed' as
                                                    "Not Executed",
                                                    'Pass' as "Pass",
                                                    'Fail' as "Fail",
                                                    'Blocked' as "Blocked"))) p;

返回:

Total   Executed    Pass    Fail    Blocked Not Executed    PRIORITY
37      36          18      11      7       1               High
32      26          18      7       1       6               Normal

我想要的是:

Status          High    Normal
Total           37      32
Executed        36      26
Pass            18      18
Fail            11      7
Blocked         7       1
Not Executed    1       6

【问题讨论】:

【参考方案1】:

首先应用unpivot,然后conditional aggregation通过ceiling函数将结果分成两组,以便能够将pivot作为Status旁边的两个额外列:

select Status as "Status", 
       max(case when ceil(rn/(cn/2))=1 then val end) as "High",
       max(case when ceil(rn/(cn/2))=2 then val end) as "Normal"
  from
  (
   select row_number() over (order by 1) as rn,
          count(*) over (order by 1) as cn,
          Status,val 
     from tab
  unpivot (val for Status in (Total, Executed, Pass, Fail, Blocked, Not_Executed))
  )
  group by status;

Demo

【讨论】:

以上是关于根据原始列之一中的值对一些新值进行分组的主要内容,如果未能解决你的问题,请参考以下文章

通过具有特定标题的列根据值对单元格进行颜色编码

如何根据列的值对熊猫数据框中的列进行分类?

如何根据相同的值对数组进行分组

如何按特定的子数组值对多维数组进行分组?

根据来自不同列的 2 个其他值对列的值求和

如何根据列的值对观察值重新编号[重复]