显示按 ID 分组的数据

Displaying data that is grouped by an ID

我正在使用 c#、asp.net、网络表单和 Visual Studio。我还使用 SQL Server Management Studio 创建我的存储过程。

如何按名为 RegId 的 ID 分组,然后显示标题列表:每个 RegId 的 URL?

我的例子table:

存储过程:

USE [MyDB]
GO
/****** Object:  StoredProcedure [dbo].[spGetRegSess]    Script Date: 8/5/2021 7:31:49 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[spGetRegSess]
       
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT *
    FROM RegSess
END

我更喜欢以文本格式显示的内容:

Bob has Google at http://www.google.com, Yahoo at http://www.yahoo.com, and MSN at http://www.msn.com.

John has Reddit at http://www.reddit.com.

我的网络表单 asp.net 页面上有这个按钮:

 <asp:Button ID="btnSend" runat="server" OnClick="btnSend_Click" Text="Send" />

单击按钮时,我从存储过程中获取数据并将其放入数据table:

protected void btnSend_Click(object sender, EventArgs e){
    DataTable dataTable = new DataTable();

    //Fill datatable
    using (SqlConnection sqlConn = new 
         SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString))
    {

        sqlConn.Open();

        using (var command = sqlConn.CreateCommand())
        {
            command.CommandType = System.Data.CommandType.StoredProcedure;
            command.CommandText = "spGetRegSess";

            SqlDataAdapter da = new SqlDataAdapter(command);
            da.Fill(dataTable);
            sqlConn.Close();
            da.Dispose();
            var myCount = dataTable.Rows.Count;
        }
        sqlConn.Close();
    }
}

这部分我卡住了。我知道我需要按 RegId 分组,但不确定这样做的语法。

您可以使用 XML Path 和 Stuff 来连接结果,如下所示:

SELECT 
  r.RegistrantId, 
  r.Name, 
  STUFF(
    (
      SELECT 
        ', ' + r2.Name + ' has ' + r2.[Whatever_Your_Column_Name_Is_here] + ' at ' + CAST(
          r2.Url AS VARCHAR(MAX)
        ) 
      FROM 
        RegSess r2 
      WHERE 
        (r2.RegistrantId = r.RegistrantId) FOR XML PATH(''), 
        TYPE
    ).value('(./text())[1]', 'VARCHAR(MAX)'), 
    1, 
    2, 
    ''
  ) AS URLs 
FROM 
  RegSess r 
GROUP BY 
  r.RegistrantId, 
  r.Name

如果您希望它按 session 分组(在您的案例中是列标题),您只需将它添加到您的分组中,如下所示:

SELECT 
  r.RegistrantId, 
  r.Name, 
  r.Title, 
  STUFF(
    (
      SELECT 
        ', ' + r2.Name + ' has ' + r2.[Whatever_Your_Column_Name_Is_here] + ' at ' + CAST(
          r2.Url AS VARCHAR(MAX)
        ) 
      FROM 
        RegSess r2 
      WHERE 
        (
          r2.RegistrantId = r.RegistrantId 
          and r2.Title = r.Title
        ) FOR XML PATH(''), 
        TYPE
    ).value('(./text())[1]', 'VARCHAR(MAX)'), 
    1, 
    2, 
    ''
  ) AS URLs 
FROM 
  RegSess r 
GROUP BY 
  r.RegistrantId, 
  r.Name, 
  r.Title

归功于@kevin-fairchild 以及他对 https://whosebug.com/a/273330/8304027

的回答