我有一张类似
的表格TRANSACTION_ID VALUE TRANSACTION_TYPE AGR_NBR PART_NBR
1 3456 BOOKING ABC1 1
2 345678 BOOKING ABC2 NULL
3 45678 BOOKING ABC1 2
4 45678 BIING ABC2 NULL
5 45678 BILLING ABC1 1
6 4775678 BILLING ABC2 NULL
我在这张桌子上运行一个简单的选择,如下所示:
SELECT AGR_NBR,PART_NBR,
CASE WHEN TRANSACTION_TYPE = 'BOOKING'
THEN SUM(VALUE)
END AS BOOKING_VAL,
CASE WHEN TRANSACTION_TYPE = 'BILLING'
THEN SUM(VALUE)
END AS BILLINNG_VAL
FROM AA_TEST_TABLE
WHERE AGR_NBR = 'ABC1'
GROUP BY AGR_NBR,PART_NBR,TRANSACTION_TYPE;
来自上述查询的输出是:
AGR_NBR PART_NBR BOOKING_VAL BILLINNG_VAL
ABC1 1 NULL 45678
ABC1 1 3456 NULL
ABC1 2 45678 NULL
但我想要的是同样的AGR_NBR&在这种情况下,像(ABC1& 1)这样的部分应该只有1行,如下所示。如果可能的话,我宁愿做一个单一的选择陈述,因为原始数据有很多公式和&加入&这也只是1行的虚拟数据,但实际上会有N行。
AGR_NBR PART_NBR BOOKING_VAL BILLINNG_VAL
ABC1 1 3456 45678
答案 0 :(得分:1)
试试这个:
SELECT A.AGR_NBR, A.PART_NBR,
SUM(CASE WHEN A.TRANSACTION_TYPE = 'BOOKING' THEN A.VALUE ELSE 0 END) AS BOOKING_VAL,
SUM(CASE WHEN A.TRANSACTION_TYPE = 'BILLING' THEN A.VALUE ELSE 0 END) AS BILLINNG_VAL
FROM AA_TEST_TABLE A
WHERE A.AGR_NBR = 'ABC1'
GROUP BY A.AGR_NBR, A.PART_NBR;
答案 1 :(得分:0)
试试这个:
SELECT AGR_NBR, PART_NBR, SUM(BOOKING_VAL) AS BOOKING_VAL, SUM(BILLING_VAL) AS BILLING_VAL FROM
(
SELECT AGR_NBR, PART_NBR, CASE WHEN TRANSACTION_TYPE = 'BOOKING' THEN SUM( VALUE ) END AS BOOKING_VAL, CASE WHEN TRANSACTION_TYPE = 'BILLING' THEN SUM( VALUE ) END AS BILLING_VAL FROM test WHERE AGR_NBR = 'ABC1' GROUP BY AGR_NBR, PART_NBR, TRANSACTION_TYPE
)
AS t GROUP BY AGR_NBR, PART_NBR