简体   繁体   中英

Oracle/SQL : count number of values and assign a number

Here is what I am trying to do. I have 2 tables:

T1:

ID     create datetime(mm/dd/yyyy hh:mm:ss)
1      17-Apr-2016
2      18-Apr-2016
3      13-Apr-2016
4      15-Apr-2016
5      20-Apr-2016
6      19-Apr-2016

T2

ID(FK) seq      create datetime(mm/dd/yyyy hh:mm:ss)
1      6546       20-Apr-2016 
1      5457       19-Apr-2016 
1      4245       18-Apr-2016
1      0
2      5567       19-Apr-2016 
2      0
3      2034       15-Apr-2016 
3      1987       14-Apr-2016 
3      1902       14-Apr-2016 
3      1249       13-Apr-2016 
3      0
4      2209       15-Apr-2016 
4      2456       16-Apr-2016 
4      3578       17-Apr-2016 
4      3467       17-Apr-2016 
4      4645       18-Apr-2016 
4      5357       19-Apr-2016 
4      0
5      0
6      0

For each ID, I want to:

  • If Id has no create time in T2/Seq =0, list ID as 'A'. eg: 5,6 would be A

  • If Id has valid seq/create time in T2:

    • then, count how many rows Id has and list the max count as B-1, B-5, B-8 and so on. eg:

      • #1 - B-3
      • #2 - B-1
      • #3 - B-4
      • #4 - B-6

I am expecting my output to be as follows:

ID   Comments
1      B-3
2      B-1
3      B-4
4      B-6
5       A
6       A

Try

SELECT id,
      CASE WHEN count( "create datetime" ) = 0
           THEN 'A'
           ELSE 'B-' || count( "create datetime" )
      END As Comments
FROM T2
GROUP BY id

You can use either case statements or Decode function in oracle.

select t1.id, decode(t2.create_date_time,0,'A',
                                        "B - "||t2.create_date_time) 
 from t1 
Left join t2
on t1.id = t2.id
group by t1.id

PS: I have not compiled above code. use Join or Left join based on your need. if you are sure that an entry would be there in t2, simple join will also work.

The following was made thinking in a scenario where there is a record on t1 and none in t2. (eg:

----+-------------
  1 | 18-Apr-2016
  2 | 18-Apr-2016
  3 | 13-Apr-2016
  4 | 15-Apr-2016
  5 | 20-Apr-2016
  6 | 19-Apr-2016
  7 | 19-Apr-2016)

Query

select 
  a.id, 
  case when inst> 0 then 'B-'||inst else 'A' end Coments
  from t1 a left outer join 
      (select id,
      count(create) inst 
      from t2 group by id) b 
  on a.id=b.id;

Execution result

 id | coments 
----+---------
  1 | B-3
  2 | B-1
  3 | B-4
  4 | B-6
  5 | A
  6 | A
  7 | A

HTH

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