我正在处理以下 SQL,我使用子查询获取一些值;我需要获得另一个值,但这有一些不同的条件:
SELECT Operator,
COUNT(*) AS 'Sales',
SUM(Commission) As 'Commission',
SUM(Fee + (2 * Commission)) As 'Amount',
SUM(Prem) As 'Prem',
FROM (
SELECT F.FormId,
F.Prem,
F.Agent,
((F.Prem/(1 + (112/100.00))) * ((PLS.Commission/100.00) * 50/100.00)) As 'Commission',
CASE WHEN F.Prem!= PLPT.Charged THEN ((F.Prem - PLPT.Charged) * (13.11/100.00))
ELSE 0
END As 'Fee'
FROM FORM F
INNER JOIN PaymentTransaction PLPT ON F.FormId = PLPT.FormId
INNER JOIN PublicScheme_backup PLS ON PLS.SchemeId = PLPT.SchemeId
WHERE Agent IS NOT NULL
AND F.TranTypeId= 6
AND Convert( date, F.Timestamp) BETWEEN '01 Jun 2024' AND '04 Jul 2024'
AND F.FormId > 1950000
) As X
GROUP BY Operator
以上查询操作员名称、销售数量、佣金、金额、预售费
Operator Sales Commission Amount Prem
--------------------------------------------------
8E 3 33.547300 94.640021 319.77
在此任务中需要获取记录计数,其中
TranTypeId = 7
将被标记为引号,但应基于每个运算符(按运算符分组)和给定的日期范围:
Operator Sales Commission Amount Prem Quotes
------------------------------------------------------------------
8E 3 33.547300 94.640021 319.77 Expected value
我尝试过以下说法:
SELECT Operator,
Count(*) AS 'Sales',
SUM(Commission) AS 'Commission',
SUM(Fee + (2 * Commission)) AS 'Amount',
SUM(Prem) AS 'Prem',
(SELECT Count(*)
FROM Form
WHERE TranTypeId = 7
AND Convert(date,Datetimestamp) BETWEEN '01 Jun 2024' AND '04 Jul 2024'
AND Operator = Operator
) AS 'Quotes'
FROM (
SELECT F.FormId,
F.Prem,
F.Agent,
((F.Prem/(1 + (112/100.00))) * ((PLS.Commission/100.00) * 50/100.00)) AS 'Commission',
CASE WHEN F.Prem!= PLPT.Charged THEN ((F.Prem - PLPT.Charged) * (13.11/100.00))
ELSE 0
END AS 'Fee'
FROM FORM F
INNER JOIN PaymentTransaction PLPT ON F.FormId = PLPT.FormId
INNER JOIN PublicScheme_backup PLS ON PLS.SchemeId = PLPT.SchemeId
WHERE Agent IS NOT NULL
AND F.TranTypeId= 6
AND Convert(date,F.Timestamp) BETWEEN '01 Jun 2024' AND '04 Jul 2024'
AND F.FormId > 1950000
) AS X
GROUP BY Operator
但我没有得到预期的结果 - 我为每个运算符得到相同的报价计数
谁能告诉我这是否正确
SELECT Operator,
Count(*) AS 'Sales',
SUM(Commission) AS 'Commission',
SUM(Fee + (2 * Commission)) AS 'Amount',
SUM(Prem) AS 'Prem',
(SELECT Count(*) FROM Form FS
WHERE TranTypeId = 7 AND FS.Operator = X.Operator
) AS 'Quotes'
FROM (
SELECT F.FormId,
F.Prem,
F.Agent,
((F.Prem/(1 + (112/100.00))) * ((PLS.Commission/100.00) * 50/100.00)) AS 'Commission',
CASE WHEN F.Prem!= PLPT.Charged THEN ((F.Prem - PLPT.Charged) * (13.11/100.00))
ELSE 0
END AS 'Fee'
FROM FORM F
INNER JOIN PaymentTransaction PLPT ON F.FormId = PLPT.FormId
INNER JOIN PublicScheme_backup PLS ON PLS.SchemeId = PLPT.SchemeId
WHERE Agent IS NOT NULL
AND F.TranTypeId= 6
AND Convert(date,F.Timestamp) BETWEEN '01 Jun 2024' AND '04 Jul 2024'
AND F.FormId > 1950000
) AS X
GROUP BY Operator
您可能需要使用条件聚合,如下所示:
SELECT Operator,
Count(*) AS 'Sales',
SUM(Commission) AS 'Commission',
SUM(Fee + (2 * Commission)) AS 'Amount',
SUM(Prem) AS 'Prem',
SUM(CASE WHEN TranTypeId = 7 THEN 1 ELSE 0 END) AS 'Quotes'
FROM (
-- Your subquery
) AS X
GROUP BY Operator