喂, 我的目标是生成一个表格,显示属于所有者的每个CODE的总数,请注意,无论TOTAL值为零,每个所有者都必须绑定一个CODE。因此APP,REJ,CAN将与每个APPROVAL_ID相关联。
APPROVAL_ID CODE TOTAL
----------- ---- -----
101 APP 2
101 REJ 1
101 CAN 3
102 APP 2
102 REJ 4
102 CAN 0
103 APP 0
103 REJ 0
103 CAN 4
因此,这是源代码:
select approval_id, code, total
from (
select 'APP' code, '1' seq from dual
union all
select 'REJ' code, '2' seq from dual
union all
select 'CAN' code, '3' seq from dual
)
left outer join (
select m.approval_id, own.name, m.decision, count(*) total,
case own.channel
when 'CH1' then 'CH1'
when 'CH2' then 'CH2'
else 'Others Channel'
end the_channel
from tableM m, owner own
where m.decision in ('REJ', 'APP', 'CAN')
and own.id=m.approval_id
group by m.approval_id, own.name, m.decision, own.channel
order by m.approval_id
)
on code=decision
group by approval_id, code, total
order by approval_id;
以上查询的输出如下:
APPROVAL_ID CODE TOTAL
----------- ---- -----
101 APP 2
101 REJ 1
101 CAN 3
102 APP 2
102 REJ 4
103 CAN 4
内部查询的输出如下:
APPROVAL_ID CODE TOTAL
----------- ---- -----
101 APP 2
101 REJ 1
101 CAN 3
102 APP 2
102 REJ 4
103 CAN 4
查询不正确,因为我知道某些行的总值为零,它应该在其中打印类似(null)的值。但为什么它隐藏在视野之外呢?我的查询有什么问题吗?
谢谢@!
答案 0 :(得分:1)
您的外部联接是代码=决定。这意味着每个代码都会得到一行,这些代码不会出现在右侧。显然,您希望使用3个代码的交叉连接和所有不同的APPROVAL_ID进行左连接,并在左侧提供代码和APPROVAL_ID的所有组合。
答案 1 :(得分:1)
首先,您需要在所有者和代码表之间进行交叉连接。 然后你做左连接。
我已经建模了3个表:输入3行APP,REJ和CAN,然后是用户表,相当于你的所有者表,第三个表决定,相当于你的tableM。
查询如下所示:
SELECT c.user_id, c.type_code, COUNT(d.id)
FROM
(
SELECT t.ID as type_id, u.id as user_id, t.CODE as type_code
FROM Type t, Userr u
) c
LEFT OUTER JOIN Decision d
ON d.user_id = c.user_id
AND d.type_id = c.type_id
GROUP BY c.user_id, c.type_code
没有经过测试,但是对于你的一套表:
select a.id_own, a.code, count(m.approval_id)
from
(
select code, own.id as id_own
from (
select 'APP' code, '1' seq from dual
union all
select 'REJ' code, '2' seq from dual
union all
select 'CAN' code, '3' seq from dual
) , owner own
) a
left outer join tableM m
on a.code = m.decision
and a.id_own = m.approval_id
group by a.id_own, a.code
order by a.id_own
请注意,count(m.approval_id)将为您提供在左连接中显示为非null的approval_id数。
答案 2 :(得分:0)
我的第一个猜测是
group by approval_id, code, total
应该是
group by approval_id, code