贷款分组50

时间:2015-07-03 19:37:41

标签: sql sql-server

我正在尝试编写一个查询,该计数将捕获0和50的计数以形成贷款的第1组,计数51和100来计算贷款的第2组等。我试图计算50个增量贷款每个人说一个银行,并将它们分为50个。我需要列出所有贷款号码。

SELECT DISTINCT 
    DLR_NAME, 
    ACCOUNT, 
    COUNT(*) AS GROUPCOUNT, 
    CASE WHEN COUNT BETWEEN 1 AND 50 Then 'Group 1'
         WHEN COUNT BETWEEN 51 AND 100 THEN 'Group 2'

像这样的东西。我目前是新手。

3 个答案:

答案 0 :(得分:3)

我不确定我是否理解正确,但试试这个:

declare @GroupSize decimal = 50.0
select BankID,
    LoanID,
    floor((_row - 1) / @GroupSize) as [GroupNum]
from (
    select BankID, 
        LoanID,
        row_number() over (partition by BankID order by BankID, LoanID) as _row
    from Loan
) a

SQL Fiddle

答案 1 :(得分:0)

不确定你真正需要什么,但也许是这样的?

select
    DLR_NAME,
    ACCOUNT,
    CASE WHEN GROUPCOUNT BETWEEN 1 AND 50 Then 'Group 1'
         WHEN GROUPCOUNT BETWEEN 51 AND 100 THEN 'Group 2'
    END
from
(
    select,
        DLR_NAME, 
        ACCOUNT,
        COUNT(*) AS GROUPCOUNT
    from
        account
    group by
        DLR_NAME, 
        ACCOUNT
) X

这将计算每个DLR_NAME + ACCOUNT在表帐户中的行数,然后根据该行分配组名。

答案 2 :(得分:0)

Select DLR_NAME, ACCOUNT , 'Group ' + Convert(varchar(10), (Convert(int, GROUPCOUNT / 50) + 1)) as Group From
(
SELECT DISTINCT 
    DLR_NAME, 
    ACCOUNT, 
    COUNT(*) AS GROUPCOUNT
From Account 
Group by DLR_NAME, ACCOUNT
)T

说明:

Convert(varchar(10), (Convert(int, GROUPCOUNT / 50) + 1))

GROUPCOUNT = 57 then 
1). Convert(varchar(10), (Convert(int, 57 / 50) + 1)) 
2). Convert(varchar(10), (Convert(int, 1.14) + 1)) 
3). Convert(varchar(10), (1 + 1)) 
4). 2 as Varchar 

对于那种情况,无需管理案例。