按总计SQL分组,用于结束周数;每月的;年初至今的数字

时间:2014-02-07 18:02:52

标签: mysql sql sql-server-2008-r2

我无法以正确的方式对每周结束,月到日和年初的总计进行分组。目前我的查询,我得到此输出

(No column name)        Received App #  Received App $  (No column name)    Loan Closed #   Loan Closed $
Applications Received   2               $500,000.00     New Loans Closed    1               $250,000.00

而不是上面,我想得到像我这样的输出

Applications Received 2  $500,000.00 
New Loans Closed      1  $250,000.00 

请参阅下面的查询:

    select 

    'Applications Received',
    count(case when pd.Status_four_Dt between '1/1/2014' and '2/1/2014' then pd.loan_amt end) as 'Received App #',
    sum(case when pd.Status_four_Dt between '1/1/2014' and '2/1/2014' then pd.loan_amt end) as 'Received App $',
    'New Loans Closed',
    count(case when pd.Status_ten_Dt between '1/1/2014' and '2/1/2014' then pd.loan_amt end) as 'Loan Closed #',
    sum(case when pd.Status_ten_Dt between '1/1/2014' and '2/1/2014' then pd.loan_amt end) as 'Loan Closed $'


    from pipe_deal pd
     left join pipe_quote pq
     on pd.id = pq.deal_id

where
pd.record_type_lkup ='dl'
and pd.company_identity_id = 2
and ((pd.status_lkup_id in(14,16,17,18,19,20,21,22,23) and pq.active_yn = 'y') or (pd.status_lkup_id = 13 and pq.active_yn is null) or (pd.status_lkup_id = 24 and (pq.active_yn = 'y' or pq.active_yn is null)))
and pd.delete_yn = 'N'
and pd.Status_One_Dt > '01/01/2008'
and (pd.EMP_OFFICE_LKUP_Id <> 192 or pd.EMP_OFFICE_LKUP_Id is null) 


--group by
--(case 
--when pd.Status_four_Dt>0  then 'Received Application'
--when  pd.Status_ten_Dt>0 then 'Loans Closed' 
--end)

所以基本上收到的应用程序和新贷款已关闭总计上周结束的一周的数字,我只是无法按照输出应该的方式对其进行分组 申请收到2 $ 500,000.00 新贷款关闭1 $ 250,000.00

我希望有一种方法可以将收到的应用程序分组,并将新贷款关闭,将它们放在行而不是列中。

请帮忙。

1 个答案:

答案 0 :(得分:0)

我对数据结构不够熟悉,无法为您提供确切的查询,但您可以使用UNION ALL完成此操作。

您只想选择应用程序接收到的数据(看似COUNT(*)和SUM(pd.loan_amt)WHERE pd.Status_four_Dt BETWEEN等)然后将结果与提供给您的那个结果联合起来给你应用程序的那个(看起来是COUNT(*)和SUM(pd.loan_amt)WHERE pd.Status_ten_Dt ...等等)。您可以只选择第一列的文本,例如,“已收到的应用程序”AS描述,COUNT(*)和SUM(贷款金额)WHERE pd.Status_four_Dt BETWEEN等,然后将结果与新贷款的结果联合起来。< / p>

有意义吗?