我找不到一种方法来划分我的2个查询的结果。
它们看起来像这样:
SELECT periode, cee_ref_no, SUM(somme) AS total FROM V_STAT_NAMUR
WHERE code_ref_no IN (1, 2, 3, 4, 5, 6, 193, 215, 237, 259, 281)
AND periode BETWEEN '201401' AND '201412'
AND cee_ref_no = '961'
GROUP BY periode, cee_ref_no
ORDER BY periode;
AND
SELECT periode, cee_ref_no, SUM(somme) AS total FROM V_STAT_NAMUR
WHERE code_ref_no IN (7, 8, 9, 10, 205, 227, 249, 271, 293)
AND periode BETWEEN '201401' AND '201412'
AND cee_ref_no = '961'
GROUP BY periode, cee_ref_no
ORDER BY periode;
它们看起来很相似,并且都返回如下内容:
DATE | CEE_REF_NO | TOTAL
201401 | 961 | 10713
201402 | 961 | 9593
... | 961 | ...
201412 | 961 | 10426
如何合并这些以获得类似的内容:
DATE | CEE_REF_NO | TOTAL
201401 | 961 | Total Q1/ Total Q2
201402 | 961 | Total Q1/ Total Q2
... | 961 | ...
201412 | 961 | Total Q1/ Total Q2
我尝试过的所有结果都只返回一行,或者返回12行,结果相同。
非常感谢!
答案 0 :(得分:0)
使用条件聚合:
SELECT periode, cee_ref_no,
SUM(CASE WHEN code_ref_no IN (1, 2, 3, 4, 5, 6, 193, 215, 237, 259, 281) THEN somme ELSE 0 END) AS total_1,
SUM(CASE WHEN code_ref_no IN (7, 8, 9, 10, 205, 227, 249, 271, 293) THEN somme ELSE 0 END) AS total_2,
(SUM(CASE WHEN code_ref_no IN (1, 2, 3, 4, 5, 6, 193, 215, 237, 259, 281) THEN somme ELSE 0 END) /
SUM(CASE WHEN code_ref_no IN (7, 8, 9, 10, 205, 227, 249, 271, 293) THEN sommeEND)
) AS ratio
FROM V_STAT_NAMUR
WHERE AND
periode BETWEEN '201401' AND '201412'
GROUP BY periode, cee_ref_no
ORDER BY periode;
答案 1 :(得分:0)
您可以尝试以下操作:
select q1.periode, q1.cee_ref_no, q1.total as Total1, q2.total as Total2, q1.total/q2.total as Division
from (
SELECT periode, cee_ref_no, SUM(somme) AS total FROM V_STAT_NAMUR
WHERE code_ref_no IN (1, 2, 3, 4, 5, 6, 193, 215, 237, 259, 281)
AND periode BETWEEN '201401' AND '201412'
AND cee_ref_no = '961'
GROUP BY periode, cee_ref_no
) q1
join (
SELECT periode, cee_ref_no, SUM(somme) AS total FROM V_STAT_NAMUR
WHERE code_ref_no IN (7, 8, 9, 10, 205, 227, 249, 271, 293)
AND periode BETWEEN '201401' AND '201412'
AND cee_ref_no = '961'
GROUP BY periode, cee_ref_no
) q2
on q1.Periode=q2.Periode
and q1.cee_ref_no=q2.cee_ref_no
基本上,您只需使用查询创建2个子选择,然后按句点和cee_ref_no将它们连接起来(如果要包括1个以上cee_ref_no,则在示例中只有一个)。然后您就可以将合计除以q1和q2。
请注意联接,我不知道您的数据是否在两个查询中都包含所有月份的信息。
PS:查询未经测试,直接在编辑器上编写。
答案 2 :(得分:0)
尝试一下
Select periode, cee_ref_no, total1/total2 as Total
From (
SELECT periode, cee_ref_no,
sum(Case when code_ref_no in (1, 2, 3, 4, 5, 6, 193, 215, 237, 259, 281) Then somme else 0 end) as total1,
sum(Case when code_ref_no in (7, 8, 9, 10, 205, 227, 249, 271, 293) Then somme else 0 end) as total2
From my_table
WHERE code_ref_no IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 193, 205, 215, 227, 237, 249, 259, 271, 281, 293)
AND periode BETWEEN '201401' AND '201412'
AND cee_ref_no = '961'
GROUP BY periode, cee_ref_no
)
ORDER BY periode;