Sql Query for get Summarize值

时间:2017-12-15 04:58:27

标签: sql sql-server

我有一个示例表,用于查找每个用户每个分支的贷款数量,使用sql server,我该怎么做

LoanID  User    Amount  Branch  Date 
001     KevinU  215000  SDC     07/9/2014 4:18:52PM
005     DenisM  520000  CVD     06/12/2014 4:18:52PM
004     KelumK  1200000 BBV     06/12/2014 4:18:52PM
002     KevinU  100000  SDC     12/9/2014 4:18:52PM

输出应该

User    NoOfLoans   Branch  Month
KevinU  2           SDC     201409

6 个答案:

答案 0 :(得分:0)

假设您使用的是MSSQL,请参阅下面的sql查询:

select user,count(loanID),branch,DATEPART(month, Date) from table_name group by user,branch,DATEPART(month, Date)

答案 1 :(得分:0)

SELECT  User,
        Count(LoanID) as NoOfLoans,
        Branch,
        concat(DATEPART(YEAR, Date), DATEPART(MONTH, Date))
FROM    MyTable
GROUP BY User, Branch,DATEPART(YEAR, Date), DATEPART(MONTH, Date);

答案 2 :(得分:0)

您也可以尝试使用此结果:

select User,count(loanID) as NoOfLoans,Branch,concat(year(Date),month(Date))
as Month from sample_table group by  User,Branch,concat(year(Date),month(Date))

答案 3 :(得分:0)

使用此

SELECT
    [User],
    [Branch],
    [Month] = CAST(YEAR([DATE]) AS VARCHAR(5))+CAST(MONTH([DATE]) AS VARCHAR(5)),
    Loans = COUNT(1)
    FROM YourTable 
        GROUP BY [User],
    [Branch],CAST(YEAR([DATE]) AS VARCHAR(5)),CAST(MONTH([DATE]) AS VARCHAR(5))

答案 4 :(得分:0)

SELECT USER,
       COUNT(*)OVER(PARTITION BY Name,Branch,Month(Date) order by Branch,Month(Date)) AS NoOfLoans,
       Branch,
       CONCAT(Year(DATE),Month(Date)) AS YearMonth FROM Table_Name 
       --WHERE USER=001

答案 5 :(得分:0)

SELECT  User,  Count(LoanID) as NoOfLoans,
Branch,DATEPART(year,date) +DATEPART(month,date) as month
FROM  Table
GROUP BY User, Branch , DATEPART(year,date) ,DATEPART(month,date)