我使用Oracle 10g和I查询包。如何在包中进行Pivot函数sum()?
Sql Query。
MF_Logg.select(fn.SUM(MF_Logg.Logg_Giva_Foder1)) \
.where((MF_Logg.Logg_RFID_ID == tag_no) & (MF_Logg.Logg_Tid > timelastday)) \
.scalar()
结果SQL查询
WITH DATA_JOIN AS
(SELECT S.START_DATE_GMT,
S.NO_OF_CALL,
S.RATE,
T.TAX_RATE,
T.EFF_DATE,
T.EXP_DATE,
S.COMPANY_CODE,
T.COMPANY_CODE CC,
S.SUB_EVENT_TYPE_ID,
S.event_type_id,
S.PMN_ORIGIN,
S.PMN_ROUTE
FROM IR_V_ISM_RATE_BY_TRANS S
LEFT JOIN IR_PMN_TAX T
ON S.COMPANY_CODE = T.COMPANY_CODE
AND S.PMN_ROUTE = T.PMN_CODE
WHERE T.TAX_TYPE = '01'
AND S.START_DATE_GMT <= T.EFF_DATE
AND S.START_DATE_GMT >= T.EXP_DATE
OR T.EXP_DATE IS NULL
ORDER BY COMPANY_CODE),
TEMP_A AS
(SELECT START_DATE_GMT,
SUM(NO_OF_CALL) AS TOTAL_TRANSACTION,
((SUM(NO_OF_CALL)) * RATE) AS TOTAL_AMOUNT,
((((SUM(NO_OF_CALL)) * RATE) * TAX_RATE) / 100) AS TOTAL_VAT,
RATE
FROM DATA_JOIN
WHERE COMPANY_CODE = 'RIT'
AND SUB_EVENT_TYPE_ID = '2'
AND PMN_ROUTE = 'C2'
AND EVENT_TYPE_ID = '01'
AND TO_CHAR(START_DATE_GMT, 'MM/YYYY') <= '01/2015'
AND (TO_CHAR(START_DATE_GMT, 'MM/YYYY') >= '01/2015' OR START_DATE_GMT IS NULL)
GROUP BY START_DATE_GMT, SUB_EVENT_TYPE_ID, RATE, TAX_RATE
ORDER BY START_DATE_GMT)
/* Result */
SELECT
SUM(TOTAL_AMOUNT)AS EXCLUDE_VAT,
SUM(TOTAL_VAT) AS SUM_VAT,
SUM(SUM(TOTAL_AMOUNT)+SUM(TOTAL_VAT)) AS TOTAL_INCLUDE
FROM TEMP_A
GROUP BY TOTAL_AMOUNT,TOTAL_VAT;
我需要Result Pivot
EXCLUDE_VAT | SUM_VAT | TOTAL_INCLUDE
5.50 | 0.30 | 5.80
包中的Pivot函数Sum()如何?
答案 0 :(得分:0)
我现在无法访问Oracle数据库,但是我记得使用带有WITH语句的PIVOT是有限制的。我可能错了。
select * from (
select 1 AS CV_ORDER,
'EXCLUDE_VAT' as CALCULATE_VAT,
SUM(TOTAL_AMOUNT) as TOTAL_AMOUNT
from TEMP_A group by 1, 'EXCLUDE_VAT'
union all
select 2 as CV_ORDER,
'SUM_VAT' as CALCULATE_VAT,
SUM(TOTAL_VAT) as TOTAL_AMOUNT
from TEMP_A group by 2, 'SUM_VAT'
union all
select 3 as CV_ORDER,
'TOTAL_INCLUDE' as CALCULATE_VAT,
SUM(TOTAL_AMOUNT) + SUM)(TOTAL_VAT) as TOTAL_AMOUNT
from TEMP_A group by 3, 'TOTAL_INCLUDE'
) order by CV_ORDER
答案 1 :(得分:0)
你需要univot,而不是pivot,但10g并不支持本机。有办法,as shown here with decode,但在这种情况下,因为你已经有了CTE,你可以将三个查询与这些查询结合起来:
/* Result */
SELECT 'EXCLUDE_VAT' AS CALCULATE_VAT,
SUM(TOTAL_AMOUNT) AS TOTAL_AMOUNT
FROM TEMP_A
UNION ALL
SELECT 'TOTAL_VAT', SUM(TOTAL_VAT)
FROM TEMP_A
UNION ALL
SELECT 'TOTAL_INCLUDE', SUM(TOTAL_AMOUNT)+SUM(TOTAL_VAT)
FROM TEMP_A;