嵌套情况时:计数检查然后格式化检查

时间:2014-06-23 14:46:02

标签: sql group-by case aggregate-functions teradata

我在TeraData中,我有两个字段f1,f2,需要以下逻辑:

    sel
         'blah' as x1,
          case when count(distinct f1) = count(distinct f2)
                 then(case when char(trim(f1)) between 1 and 25
                             then 'OK'
                           else 'DEFECT_1'
                      end)
               else 'DEFECT_2'
             end as x2,
           count(x2) as x3
     from table
     group by 1, 2

这会引发错误,因为group by语句中不允许使用聚合函数。如何在长度检查之前解决这个问题?

谢谢!


编辑以澄清:

这是一个较大的SQL的一部分,用于检查数据集中的各种格式。输出是一堆联合(每个检查一个选择),每个形式:

          check_n  | OK       | count(OK)
          check_n  | DEFECT_1 | count(DEFECT_1)
          check_n  | ...      | ...
          check_n  | DEFECT_m | count(DEFECT_m)
          check_n+1| ...      | ...

但对于这一点,我想产生以下结果:

          check_k  | OK       | count(OK)
          check_k  | DEFECT_1 | count(DEFECT_1)
          check_k  | DEFECT_2 | NULL

1 个答案:

答案 0 :(得分:0)

我认为有一种方法可以通过简单的查询获得结果,但这应该有用(尽管它绝对不是很有效):

sel
     'blah' as x1,
      case when (SELECT count(distinct f1) - count(distinct f2) FROM table) = 0
             then(case when char(trim(f1)) between 1 and 25
                         then 'OK'
                       else 'DEFECT_1'
                  end)
           else 'DEFECT_2'
         end as x2,
       count(x2) as x3
 from table
 group by 1, 2

更复杂但也更有效应该是:在一行中计算所有三个可能的结果,然后对两行表进行条件连接(这里使用sys_calendar):

SELECT 
   x1,
   CASE
      WHEN is_equal = 'N' THEN 'Defect_2' 
      WHEN n = 1 THEN 'Defect_1'
      ELSE 'OK'
   END,
   CASE
      WHEN is_equal = 'N' THEN cnt
      WHEN n = 1 THEN cnt - cntcase
      ELSE cnt
   END AS x
FROM
 (
   SEL 'blah' AS x1,
       COUNT(CASE WHEN (CHAR(TRIM(f1))) BETWEEN 1 AND 25 THEN 1 END) AS cntcase,
       COUNT(*) AS cnt,
       CASE WHEN COUNT(DISTINCT f1) = COUNT(DISTINCT f2)
            THEN 'Y' 
            ELSE 'N'
       END AS is_equal
   FROM TABLE
   GROUP BY 1
 ) AS dt
JOIN (SELECT day_of_calendar AS n FROM sys_calendar.CALENDAR WHERE n BETWEEN 1 AND 2) AS t2
ON (n = 1 OR (is_equal = 'Y'))
AND x > 0