在我的数据库中,我有此数据。现在,我想根据日期和按roll_number分组查询和获取数据。我可以使用
获取所有数据select * from attendance_records where intake='36-1'
但是我找不到我想要的。我正在学习数据库和SQL。我使用了如下所示的分组选项,但结果不是我想要的。请让我知道我如何获得我在第二张照片中添加的结果。这将对我的数据库学习有很好的帮助。
select * from attendance_records where intake='36-1' group by date
但是以上查询仅提供一个学生信息。我找不到我想要的。
此作品:
SELECT * INTO #attendance_records
FROM
(
SELECT 69 ID,'snaha sadhu' student_name, 16 roll_number, '36-1' intake, 1 attendence_status, CONVERT(VARCHAR(10), getdate(), 103) date
UNION ALL
SELECT 70 ID,'keya' student_name, 37 roll_number, '36-1' intake, 0 attendence_status, CONVERT(VARCHAR(10), getdate(), 103) date
union
SELECT 69 ID,'snaha sadhu' student_name, 16 roll_number, '36-1' intake, 1 attendence_status, CONVERT(VARCHAR(10), dateadd(day,1,getdate()), 103) date
UNION ALL
SELECT 70 ID,'keya' student_name, 37 roll_number, '36-1' intake, 1 attendence_status, CONVERT(VARCHAR(10), dateadd(day,1,getdate()), 103) date
)TAB
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
SELECT @ColumnName= ISNULL(@ColumnName + ',','') + '[' + [date] + ']'
FROM (select distinct [date] from #attendance_records) s
SET @DynamicPivotQuery =
N'select *, cast(CONVERT(DECIMAL(18,2),CONVERT(DECIMAL(18,2),' + @ColumnName + ')/CONVERT(DECIMAL(18,2),(select COUNT(distinct [date]) from #attendance_records)))*100 as varchar(10))+''%''
from
(SELECT student_name, roll_number, intake, ' + @ColumnName + '
FROM #attendance_records
PIVOT( sum(attendence_status)
FOR [date] IN (' + @ColumnName + '))
AS P) x'
EXEC sp_executesql @DynamicPivotQuery