简体   繁体   中英

How to display for last 5 days audit record in the DB2 through an SQL statement day wise and show count of them day wise in a single row

For the admin I performing certain type of sql operation. Records are of the following type.

date        number of failed login
13/02/2017            1
12/02/2017            2
11/02/2017            0
10/02/2017            9
09/02/2017            0

I want the 0,9,0,2,1 in a single row.

I have tried the below query. But failed to get the zero by default. On which user day the user has performed zero operation has to be there.

select LISTAGG(cnt, ', ') 
from (select count(*) as cnt 
      from OPERATIONINFO 
      where OPERATIONTYPE='FAILEDLOGIN' 
        and CUSTID = 123 
        and date(UPDATEDDATEOFLOGIN) > (current date - 5 day)  
      group by YEAR(date), MONTH(date), DAY(date) 

Please help.

You need to pivot the data using decode. have a look at this example which takes this

INSERT INTO Sales VALUES
(2004, 1, 20),
(2004, 2, 30),
(2004, 3, 15),
(2004, 4, 10),
(2005, 1, 18),
(2005, 2, 40),
(2005, 3, 12),
(2005, 4, 27);

to this

Year Q1 Q2 Q3 Q4
---- -- -- -- --
2004 20 30 15 10
2005 18 40 12 27

by using decode in db2

SELECT Year,
       MAX(DECODE(Quarter, 1, Results)) AS Q1,
       MAX(DECODE(Quarter, 2, Results)) AS Q2,            
       MAX(DECODE(Quarter, 3, Results)) AS Q3,
       MAX(DECODE(Quarter, 4, Results)) AS Q4
  FROM Sales
  GROUP BY Year;

You need a dates table... here I make on on the fly using recursion -- not the best way...

WITH DATES_TABLE AS 
(
   SELECT CURRENT DATE - 5 DAYS AS D FROM SYSIBM.SYSDUMMY1

   UNION ALL

   SELECT D + 1 DAY AS D FROM DATES_TABLE WHERE D < CURRENT DATE
), THE_DATA AS
(
  select D.D, SUM(CASE WHEN O.UPDATEDDATEOFLOGIN IS NOT NULL THEN 1 ELSE 0 END) as cnt 
  from DATES_TABLE D
  LEFT JOIN OPERATIONINFO O ON O.UPDATEDDATEOFLOGIN = D.D
  where O.OPERATIONTYPE='FAILEDLOGIN' 
    and O.CUSTID = 123 
  group by D.D

)
select  LISTAGG(cnt, ', ') 
from THE_DATA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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