Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You are going to need to use dynamic SQL to figure out which columns you want to display, unless you know the full set of possible nationality values.</p> <pre><code>DECLARE @start DATETIME, @end DATETIME; SET @start = '20120802'; SET @end = '20120802'; DECLARE @sql NVARCHAR(MAX); SET @sql = N'SELECT Room_No, Study_Date, Male = SUM(CASE WHEN Student_Sex = ''Male'' THEN 1 ELSE 0 END), Female = SUM(CASE WHEN Student_Sex = ''Female'' THEN 1 ELSE 0 END)'; SELECT @sql = @sql + CHAR(13) + CHAR(10) + ',' + Nationality + ' = SUM(CASE WHEN Nationality = ''' + Nationality + ''' THEN 1 ELSE 0 END)' FROM dbo.vStudent WHERE Nationality IS NOT NULL GROUP BY Nationality; SET @sql = @sql + ' FROM dbo.vStudent WHERE Study_Date &gt;= ''' + CONVERT(CHAR(8), @start, 112) + ''' AND Study_Date &lt; ''' + CONVERT(CHAR(8), DATEADD(DAY, 1, @end), 112) + ''' GROUP BY Room_No, Study_Date;'; EXEC sp_executesql @sql; </code></pre> <p>If the set of nationalities is known, then you can simply say:</p> <pre><code>SELECT Room_No, Study_Date, Male = SUM(CASE WHEN Student_Sex = 'Male' THEN 1 ELSE 0 END), Female = SUM(CASE WHEN Student_Sex = 'Female' THEN 1 ELSE 0 END), Cambodian = SUM(CASE WHEN Nationality = 'Cambodian' THEN 1 ELSE 0 END), Chinese = SUM(CASE WHEN Nationality = 'Chinese' THEN 1 ELSE 0 END), Thailand = SUM(CASE WHEN Nationality = 'Thailand' THEN 1 ELSE 0 END) -- continue other nationalities here FROM dbo.vStudent WHERE Study_Date &gt;= @start AND Study_Date &lt; DATEADD(DAY, 1, @end) GROUP BY Room_No, Study_Date; </code></pre> <p>You could probably do this a little more elegantly with <code>PIVOT</code>, but it really depends on your definition of "elegant." See the <a href="http://msdn.microsoft.com/en-us/library/ms177410%28v=sql.90%29.aspx" rel="nofollow">docs here</a>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload