Here's how to normalize your data, which will make querying it a lot easier.
Using a table definition, I inserted your data
INSERT INTO test(Datedif,hour1,subject1,faculty1,hour2,subject2,faculty2,hour3,subject3,faculty3,batch) VALUES ('30-06-2015',1,'Maths','Kevin',1,'Maths','Kevin',1,'Science','Amal','BBA'), ('30-06-2015',1,'Science','Amal',1,'Science','Amal',1,'Maths','Kevin','MBA');
Then I created a new normalized structure for your data with narrower data types. This helps keep your data clean and also does not waste storage space, which means that requests will be faster because they donβt need to process so much data.
CREATE TABLE new_test ( dt DATE NULL, hr TINYINT NULL, --holds values between 0 to 255 subj VARCHAR(100) NULL, --plenty big enough. No need for NVARCHAR unless you are using Unicode characters faculty VARCHAR(100) NULL, attendance BIT NULL, dayweek TINYINT NULL, weekmonth TINYINT NULL, section VARCHAR(100) NULL, --not sure what this is sess VARCHAR(100) NULL, --not sure what this is batch CHAR(3) NULL --looks like there are three character codes );
Here I am normalizing the data. I am not sure if you have attendance of 2,3,4 etc. If you do in your actual table, then you should fix my code.
Note: I calculated the daily week and week from the date. I did my best if they are incorrect, then feel free to correct them.
WITH norm_data AS ( SELECT datedif,hour1,subject1,faculty1,attendence1,dayweek,weekmonth,section,[session],batch FROM test UNION ALL SELECT datedif,hour2,subject2,faculty2,attendence1,dayweek,weekmonth,section,[session],batch FROM test UNION ALL SELECT datedif,hour3,subject3,faculty3,attendence1,dayweek,weekmonth,section,[session],batch FROM test UNION ALL SELECT datedif,hour4,subject4,faculty4,attendence1,dayweek,weekmonth,section,[session],batch FROM test UNION ALL SELECT datedif,hour5,subject5,faculty5,attendence1,dayweek,weekmonth,section,[session],batch FROM test ) INSERT INTO new_test SELECT PARSE(datedif AS DATE USING 'de-DE') AS [datedif], hour1, subject1, faculty1, attendence1, DATEPART(WEEKDAY,PARSE(datedif AS DATE USING 'de-DE')) AS dayweek, datepart(day, datediff(day, 0, PARSE(datedif AS DATE USING 'de-DE'))/7 * 7)/7 + 1 AS weekmonth, section, [session], batch FROM norm_data
Now look at your new table
SELECT * FROM new_test
If this is correct, then here's how to rename tables
EXEC SP_rename @objname = 'test', --if you don't want to drop the old table @newname = 'test_old' EXEC SP_rename @objname = 'new_test', --now give the new table the actual name @newname = 'test' SELECT * FROM test