如何使用asp.net垂直获取SQL水平数据库值

本文关键字:SQL 水平 数据库 获取 垂直 何使用 asp net | 更新日期: 2023-09-27 17:49:15

我在SQL server中有一个表,如下所示

studentid     subject    marks
    1          telugu      70
    1         english      80
    1           maths       90
    1           social      70

我想在gridview中显示上面的表,如下所示

 studentid   telugu   english   maths   social    total 
    1            70       80         90      70      310 

我尝试使用如下数据表

我动态地创建了dataccolumns,如下所示

while (dr.Read())
            {
               dt.Columns.Add(dr["subname"].ToString(), typeof(string));
            }

但不知道如何动态插入标记,如上图所示…

thanks in advance....

如何使用asp.net垂直获取SQL水平数据库值

另一种方法是使用CASE

 SELECT studentid
        ,MAX(CASE WHEN subject = 'telugu' THEN marks END) AS telugu
        ,MAX(CASE WHEN subject = 'english' THEN marks END) AS english
        ,MAX(CASE WHEN subject = 'maths' THEN marks END) AS maths
        ,MAX(CASE WHEN subject = 'social' THEN marks END) AS social
        ,SUM(marks) AS Total
 FROM yourTable
 GROUP BY studentid

下面是一个使用pivot(数据库端解决方案)的解决方案:

IF(OBJECT_ID('Example','U') IS NOT NULL)
    DROP TABLE Example
CREATE TABLE Example (studentid INT,subject VARCHAR(30), marks INT)
INSERT INTO Example VALUES
(1,'telugu',70),
(1,'english',80),
(1,'maths',90),
(1,'social',70),
(2,'telugu',70),
(2,'english',80),
(2,'maths',90),
(2,'social',70)
SELECT studentid,[telugu],[english],[maths],[social] FROM Example
PIVOT
(
    MAX(marks)
    FOR subject IN ([telugu],[english],[maths],[social])
) AS pvt