子查询由销售人员从不同的表和组中提取总金额

时间:2018-03-28 14:51:26

标签: sql

- 我试图简单地添加一个子查询来获取每个销售人员与其报价相关的总销售额。我很茫然,希望有人可以提供帮助。

select sp.FIRST_NAME + ' ' + sp.LAST_NAME,
sum(case when sq.SAL_QUOTE_STATUS_ID = '1' then 1 else 0 end) as [Created],
sum(case when sq.SAL_QUOTE_STATUS_ID = '4' then 1 else 0 end) as [Ordered],
sum(case when sq.SAL_QUOTE_STATUS_ID = '3' then 1 else 0 end) as [Rejected],
sum(sq.AMOUNT_INCLUDING_TAX) as [Amount],
sum(sq.COST) as [Cost],
sum(sq.AMOUNT_INCLUDING_TAX - sq.COST) as [Profit],
round(100 * (case when sum(sq.AMOUNT_INCLUDING_TAX) > 0 then 
(sum(sq.AMOUNT_INCLUDING_TAX) -
    sum(sq.COST)) / sum(sq.AMOUNT_INCLUDING_TAX) else 0 end), 3) as [GP%],
    (Select sum(so.amount_including_tax)
     from SAL_SALES_ORDER so
     where so.SALESPERSON_ID = sp.SALESPERSON_ID) as [YTD Sales]
from SAL_SALES_QUOTE sq
inner join CRM_SALESPERSON sp on sp.SALESPERSON_ID = sq.SALESPERSON_ID
where sq.CREATED_DATE > '01-01-2018'
group by sp.FIRST_NAME + ' ' + sp.LAST_NAME

1 个答案:

答案 0 :(得分:0)

我将你的子查询从select中取出,将其作为一个结果集加入,然后从中拉出总和。

select sp.FIRST_NAME + ' ' + sp.LAST_NAME,
sum(case when sq.SAL_QUOTE_STATUS_ID = '1' then 1 else 0 end) as [Created],
sum(case when sq.SAL_QUOTE_STATUS_ID = '4' then 1 else 0 end) as [Ordered],
sum(case when sq.SAL_QUOTE_STATUS_ID = '3' then 1 else 0 end) as [Rejected],
sum(sq.AMOUNT_INCLUDING_TAX) as [Amount],
sum(sq.COST) as [Cost],
sum(sq.AMOUNT_INCLUDING_TAX - sq.COST) as [Profit],
round(100 * (case when sum(sq.AMOUNT_INCLUDING_TAX) > 0 then 
(sum(sq.AMOUNT_INCLUDING_TAX) -
    sum(sq.COST)) / sum(sq.AMOUNT_INCLUDING_TAX) else 0 end), 3) as [GP%],
sum([x.ytd_sales]) AS YTD_Sales
from SAL_SALES_QUOTE sq
inner join CRM_SALESPERSON sp on sp.SALESPERSON_ID = sq.SALESPERSON_ID
inner join (Select so.salesperson_id, sum(so.amount_including_tax) AS [YTD Sales]
         from SAL_SALES_ORDER so
         group by so.salesperson_id) x
ON x.salesperson_id = sp.salesperson_id
where sq.CREATED_DATE > '01-01-2018'
group by sp.FIRST_NAME + ' ' + sp.LAST_NAME