需要使用分组和在Oracle中查询以下内容

时间:2019-04-14 04:44:07

标签: sql oracle

我有一个如下表。

12-APR-19 06.48.08.883000 PM,AWSA
12-APR-19 06.48.41.208000 PM,
12-APR-19 07.24.55.697334 PM,ER
11-APR-19 08.58.34.835000 AM,AWSA
10-APR-19 08.10.38.675052 PM,ER
19-APR-19 09.48.14.597000 AM,

.........

尝试了以下查询。

SELECT TO_CHAR(register_date,'DD-MON-YY') || ',' || 
   reg_type || ',' || COUNT(*)
FROM po_ta_oam_customer
WHERE register_date >= '01-APR-19' AND register_date < '08-APR-19'
GROUP BY TO_CHAR(register_date,'DD-MON-YY'),
         reg_type
ORDER BY TO_CHAR(register_date,'DD-MON-YY');

我得到如下结果。

 1-Apr-19   AWSA    1222
 1-Apr-19   ER  34
 1-Apr-19       2556
 2-Apr-19   AWSA    1062
 2-Apr-19   ER  22
 2-Apr-19       2431
 3-Apr-19   AWSA    1037
 3-Apr-19   ER  33
 3-Apr-19       2521
 4-Apr-19   AWSA    920
 4-Apr-19   ER  36
 4-Apr-19       2359
 5-Apr-19   AWSA    832
 5-Apr-19   ER  20
 5-Apr-19       2091
 6-Apr-19   AWSA    476
 6-Apr-19   ER  18
 6-Apr-19       1673
 7-Apr-19   AWSA    50
 7-Apr-19   ER  15
 7-Apr-19       1555

但是我试图得到如下结果。

   Date     AWSA    ER  Blanks
 1-Apr-19   1222    34  2556
 2-Apr-19   1062    22  2431
 3-Apr-19   1037    33  2521
 4-Apr-19   920     36  2359
 5-Apr-19   832     20  2091
 6-Apr-19   476     18  1673
 7-Apr-19   50      15  1555

2 个答案:

答案 0 :(得分:0)

您可以使用conditional aggregation

SELECT TO_CHAR(register_date,'DD-MON-YY')              as "Date",
       COUNT( CASE WHEN reg_type = 'AWSA' THEN 1 END ) as AWSA,
       COUNT( CASE WHEN reg_type = 'ER'   THEN 1 END ) as ER,
       COUNT( CASE WHEN reg_type = '  '   THEN 1 END ) as "Blank"
  FROM po_ta_oam_customer
 WHERE register_date BETWEEN '01-APR-19' AND '07-APR-19'
 GROUP BY TO_CHAR(register_date,'DD-MON-YY')             
 ORDER BY "Date";

P.S。我不确定正在构造reg_type = ' '列的"Blank"归类中空格字符的长度,似乎有2个字符。长度,我就这样离开了。

答案 1 :(得分:0)

这确实是Barbaros回答的一种变体。但我建议:

SELECT TO_CHAR(register_date, 'DD-MON-YY') as "Date",
       SUM(CASE WHEN reg_type = 'AWSA' THEN 1 ELSE 0 END ) as AWSA,
       SUM(CASE WHEN reg_type = 'ER' THEN 1 ELSE 0 END) as ER,
       SUM(CASE WHEN TRIM(reg_type) IS NULL THEN 1 ELSE 0 END) as Blank
FROM po_ta_oam_customer
WHERE register_date >= DATE '2019-04-01' AND
      register_date < DATE '2019-04-08'
GROUP BY TO_CHAR(register_date, 'DD-MON-YY')             
ORDER BY MAX(register_date);

注意:

  • 日期常数作为日期常数而不是字符串输入。 Oracle支持此功能,并使查询更清晰。
  • 包括4月7日的所有数据。
  • ORDER BY的有效期超过一个月。
  • Blank的计算适用于任意数量的空格或NULL值。