如何在SQL SELECT语句中按特定列计数记录并将该值放入该行的另一列

时间:2017-11-21 16:48:48

标签: sql sql-server

我正在尝试在同一个学生的AppNum列中输入一个计数值,其中结果集中的FIRST / TOP记录为1,后续记录为2,3等。我尝试使用GROUP执行此操作但是没有得到我正在寻找的结果。在下面的PIC中,第一个结果集显示了我得到的结果,第二个结果集是我需要的。

以下是我要做的PIC:

Count Question

我试图获得正确结果集的查询如下。任何帮助/方向将不胜感激:

SELECT 
    StudentID, Location, Status, EconomicDisadvantageCode, 
    StatusEffectiveDate, Enddate, SchoolYear, ApplicationTypeCode, 
    LastUpdated, UpdatedAppType, DataSource, COUNT(Status) AS AppNum
FROM 
    #MCS_5
WHERE 
    StudentID IN (SELECT StudentID 
                  FROM #MCS_5 
                  GROUP BY StudentID 
                  HAVING COUNT(StudentID) > 1)
GROUP BY 
    Status, StudentID, Location, Status, EconomicDisadvantageCode, 
    StatusEffectiveDate, Enddate, SchoolYear, ApplicationTypeCode, 
    LastUpdated, UpdatedAppType, DataSource
ORDER BY 
    StudentID ASC, StatusEffectiveDate ASC;

2 个答案:

答案 0 :(得分:3)

使用row_number功能,在这种情况下非常方便。

SELECT StudentID
    ,Location
    ,STATUS
    ,EconomicDisadvantageCode
    ,StatusEffectiveDate
    ,Enddate
    ,SchoolYear
    ,ApplicationTypeCode
    ,LastUpdated
    ,UpdatedAppType
    ,DataSource
    ,ROW_NUMBER () OVER (PARTITION BY Studentid,STATUS ORDER BY [STATUS]) 
     Appnum
FROM #MCS_5
WHERE StudentID IN (
        SELECT StudentID
        FROM #MCS_5
        GROUP BY StudentID
        HAVING COUNT(StudentID) > 1
        )

答案 1 :(得分:0)

只需使用窗口函数:

Select ...
From (select t.*,
             Row_number() over (partition by studentid order by status) as seqnum,
             Count(*) over (partition by studentid) as cnt
      From #mcd_5 t
     ) t
Where cnt > 1