【发布时间】:2018-05-08 07:01:22
【问题描述】:
我目前因一个复杂的请求(加入)而被阻止:
我有这张表“DATA”:
order | product
----------------
1 | A
1 | B
2 | A
2 | D
3 | A
3 | C
4 | A
4 | B
5 | Y
5 | Z
6 | W
6 | A
7 | A
还有这个表“DICO”:
order | couple | first | second
-------------------------------
1 | A-B | A | B
2 | A-D | A | D
3 | A-C | A | C
4 | A-B | A | B
5 | Y-Z | Y | Z
6 | W-A | W | A
我想在一行中获得:
order | count | total1stElem | %1stElem | total2ndElem | %2ndElem
------------------------------------------------------------------
A-B | 2 | 6 | 33% | 2 | 100%
A-D | 1 | 6 | 16% | 1 | 100%
A-C | 1 | 6 | 16% | 1 | 100%
Y-Z | 1 | 1 | 100% | 1 | 100%
W-A | 1 | 1 | 100% | 6 | 16%
信息:
Fields: (On the 1st Line example)
total1stElem : count ALL('A') in table Data (all occurrences of A in Data)
total2ndElem : count ALL('B') in table Data (all occurrences of B in Data)
Count : count the number of 'A-B' occurence in table Dico
%1stElem = ( Count / total1stElem ) * 100
%1ndElem = ( Count / total2ndElem ) * 100
我是基于这个要求:
select couple, count(*),
sum(count(*)) over (partition by first) as total,
(count(*) * 1.0 / sum(count(*)) over (partition by first) ) as ratio
from dico1
group by couple, first ORDER BY ratio DESC;
我想做类似的事情:
select couple, count(*) as COUNT,
count(*) over (partition by product #FROM DATA WHERE product = first#) as total1stElem,
(count(*) * 1.0 / sum(count(*)) over (partition by product #FROM DATA WHERE product = first#) as %1stElem
count(*) over (partition by product #FROM DATA WHERE product = second#) as total2ndElem,
(count(*) * 1.0 / sum(count(*)) over (partition by product #FROM DATA WHERE product = second#) as %2ndElem
from dico1
group by couple, first ORDER BY COUNT DESC;
我的请求的关节部分完全被阻止了。有人可以帮助我吗?我在 Oracle 上得到了此类或请求的帮助,但不幸的是,无法在 PostgreSQL 中调整 UNPIVOT 和 PIVOT 函数。
【问题讨论】:
-
您能解释一下
total1stElem、total2ndElem的值是如何计算的吗? -
真的不清楚。请添加您尝试过的查询并解释更多
-
感谢您的推荐,我尽力解释得更好。
标签: sql postgresql join group-by percentage