我有以下表格:
用户组
usergrp_id bigint Primary Key
usergrp_name text
用户
user_id bigint Primary Key
user_name text
user_usergrp_id bigint
user_loc_id bigint
user_usergrp_id
有来自 user_group 表
user_loc_id
的对应 id 有来自分支表的对应 id(branch_id)。
分支
branch_id bigint Primary Key
branch_name text
branch_type smallint
branch_type
默认设置为 1。尽管它可能包含 1 到 4 之间的任何值。
用户项目
proj_id bigint Primary Key
proj_name text
proj_branch_id smallint
proj_branch_id
从分支表中具有相应的 id(branch_id)。
user_approval
appr_id bigint Primary Key
appr_prjt_id bigint
appr_status smallint
appr_approval_by bigint
appr_approval_by
具有来自用户表的相应 id(user_id)
appr_status
可能包含不同的状态值,例如 10,20,30... 对于单个appr_prjt_id
用户组
usergrp_id | usergrp_name
-------------------------
1 | Admin
2 | Manager
用户
user_id | user_name | user_usergrp_id |user_loc_id
---------------------------------------------------
1 | John | 1 | 1
2 | Harry | 2 | 1
分支
branch_id | branch_name | branch_type
-------------------------------------
1 | location1 | 2
2 | location2 | 1
3 | location3 | 4
4 | location4 | 2
5 | location4 | 2
用户项目
proj_id | proj_name | proj_branch_id
------------------------------------
1 | test1 | 1
2 | test2 | 2
3 | test3 | 1
4 | test4 | 3
5 | test5 | 1
6 | test5 | 4
user_approval
appr_id | appr_prjt_id | appr_status | appr_approval_by
-------------------------------------------------------
1 | 1 | 10 | 1
2 | 1 | 20 | 1
3 | 1 | 30 | 1
4 | 2 | 10 | 2
5 | 3 | 10 | 1
6 | 3 | 20 | 2
7 | 4 | 10 | 1
8 | 4 | 20 | 1
条件:输出必须取for each的MAX()
值并计数。appr_status
appr_prjt_id
即,在上表中appr_prjt_id=1
有 3 种不同的状态:10、20、30。它的计数必须只显示在输出中对应于 30 的状态(不在状态 10 和 20 中),对应于特定的用户组branch_name
。同样对于该字段中的每个其他 idappr_prjt_id
期望的输出:
10 | 20 | 30
------> Admin 0 | 1 | 1
|
location1
|
------> Manager 1 | 1 | 0
我怎样才能做到这一点?