我有两个表格。在第一个是为谁和何时开始某种类型的折扣的数据(有8种类型的折扣,但我们将它们分为两类)。折扣活跃6个月,但每月减少,折扣的开始日期对每个人不同。 第二个表是交易。
我想知道有多少交易以及第一类折扣和第二类人员在第一个月,第二个等方面做了多少交易。
SELECT (CASE WHEN Trunc(Months_Between(A.DATE_TRANS, B.DATA_DISCOUNT))=0 THEN 0
WHEN Trunc(Months_Between(A.DATE_TRANS, B.DATE_DISCOUNT))=1 THEN 1
WHEN Trunc(Months_Between(A.DATE_TRANS, B.DATE_DISCOUNT))=2 THEN 2
WHEN Trunc(Months_Between(A.DATE_TRANS, B.DATE_DISCOUNT))=3 THEN 3
WHEN Trunc(Months_Between(A.DATE_TRANS, B.DATE_DISCOUNT))=4 THEN 4
WHEN Trunc(Months_Between(A.DATE_TRANS, B.DATE_DISCOUNT))=5 THEN 5
END)
AS MONTH,
CASE WHEN A.TYPE IN (5,6,7,8) THEN COUNT(A.PRICE)
END AS COUNT_TRANS_1,
CASE WHEN A.TYPE IN (5,6,7,8) THEN SUM(A.PRICE)
END AS SUM_PRICE_1,
CASE WHEN A.TYPE IN (1,2,3,4) THEN COUNT(A.PRICE)
END AS COUNT_TRANS_2,
CASE WHEN A.TYPE IN (1,2,3,4) THEN SUM(A.PRICE)
END AS SUM_PRICE_2
from DATABASE_1 A join DATABASE_2 B
on A.ID=B.ID
where Trunc(Months_Between(A.DATE_TRANS, B.DATE_DISCOUNT)) IN (0,1,2,3,4,5)
GROUP BY A.ID, MONTH
答案 0 :(得分:0)
尝试了解您的需求,也许您需要以下内容:
SELECT Trunc(Months_Between(A.DATE_TRANS, B.DATE_DISCOUNT)) AS MONTH,
COUNT(
CASE
WHEN A.TYPE IN (5,6,7,8)
THEN A.PRICE
ELSE NULL
END
) AS COUNT_TRANS_1,
SUM(
CASE
WHEN A.TYPE IN (5,6,7,8)
THEN A.PRICE
ELSE 0
END
) AS SUM_PRICE_1,
COUNT(
CASE
WHEN A.TYPE IN (1,2,3,4)
THEN A.PRICE
ELSE NULL
END
) AS COUNT_TRANS_2,
SUM(
CASE
WHEN A.TYPE IN (1,2,3,4)
THEN A.PRICE
ELSE 0
END
) AS SUM_PRICE_2
from DATABASE_1 A join DATABASE_2 B
on A.ID=B.ID
where Trunc(Months_Between(A.DATE_TRANS, B.DATE_DISCOUNT)) IN (0,1,2,3,4,5)
GROUP BY A.ID, Trunc(Months_Between(A.DATE_TRANS, B.DATE_DISCOUNT))
我不确定您是否需要按ID分组,请检查它。