如何格式化父子记录的结果集?

时间:2009-09-03 14:33:59

标签: .net sql-server ado.net sorting

所有

我有一个来自多个SQL Server表的结果集,我需要知道获取所需的排序记录的最佳方法是什么。

我有以下记录;用户名和模块号作为父记录,然后对于每个模块,有多个子模块子记录。我遇到的问题是模块记录与每个子模块记录有关联。因此,我从我的存储过程中得到以下记录:

NAME            Module  Sub-module
Derek Kenney    1       1
Derek Kenney    1       2
Derek Kenney    1       3
Derek Kenney    1       4
Derek Kenney    1       5

我想要的是:

NAME            Module  Sub-module
Derek Kenney    1       1
                        2
                        3
                        4
                        5

我认为我的问题属于我在下面发布的问题。


ALTER PROCEDURE [dbo].[uspGetReportData]

AS
BEGIN
    SELECT first_name, last_name, email, country_id, T_User_Info.user_id, T_Modules_Viewed.module_id as 'modules viewed', T_Modules_Completed.module_id as 'modules completed'
     FROM T_User_Info inner join T_Modules_Viewed on T_User_Info.user_id = T_Modules_Viewed.user_id left outer join T_Modules_Completed
 on T_Modules_Viewed.user_id = T_Modules_Completed.user_id
END

也许在ADO.NET中有一种方法可以获得我想要的结果集,而我却不知道它。任何帮助将不胜感激。

德里克肯尼

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

DECLARE @YourData table (YourName varchar(20), Module char(1), SubModule char(1))

INSERT INTO @YourData VALUES ('Derek Kenney',1,1)
INSERT INTO @YourData VALUES ('Derek Kenney',1,2)
INSERT INTO @YourData VALUES ('Derek Kenney',1,3)
INSERT INTO @YourData VALUES ('Derek Kenney',1,4)
INSERT INTO @YourData VALUES ('Derek Kenney',1,5)
INSERT INTO @YourData VALUES ('Derek Kenney',2,1)
INSERT INTO @YourData VALUES ('Derek Kenney',2,2)
INSERT INTO @YourData VALUES ('Derek Kenney',2,3)
INSERT INTO @YourData VALUES ('Joe Smith'   ,1,1)
INSERT INTO @YourData VALUES ('Joe Smith'   ,2,1)
INSERT INTO @YourData VALUES ('Joe Smith'   ,2,2)


SELECT
    CASE WHEN NameRank=1 /*OR NameModuleRank=1*/ THEN YourName ELSE '' END AS YourName
        ,CASE NameModuleRank WHEN 1 THEN Module ELSE '' END AS Module
        ,SubModule
    FROM (SELECT
              YourName,Module,SubModule
                  ,ROW_NUMBER() OVER(partition by YourName ORDER BY YourName) AS NameRank
                  ,ROW_NUMBER() OVER(partition by YourName,Module ORDER BY YourName,Module) AS NameModuleRank
              FROM @YourData
         ) dt

输出:

YourName             Module SubModule
-------------------- ------ ---------
Derek Kenney         1      1
                            2
                            3
                            4
                            5
                     2      1
                            2
                            3
Joe Smith            1      1
                     2      1
                            2

(11 row(s) affected)

如果需要,可以取消注释案例中的OR,以便在模块更改时显示YourName