View Single Post
Old 08-13-2004, 07:22 PM   #4 (permalink)
magua
Tilted
 
If I'm reading you right, what you want to do is pivot the data; ie, transform

Code:
User     Section     Access
--------------------------------
Bob       Sec 1        1
Bob       Sec 2        1
Bob       Sec 3        0
Into

Code:
User     Section 1     Section 2     Section 3
Bob       1                 1                  0
Right? Unfortunately, you don't say which db you're using, or what programming language (if any). There's a way to do what you want, but it requires the ability to concatenate strings, and the SQL has to understand the CASE statement. This is valid in SQL Server; you're on your own trying to port it. The string concatenation I'm doing in SQL Server syntax for simplicity; you could just as easily do it in any programming language, and pass it to the db.

Code:
DECLARE @SQL varchar(4000)

SET @SQL = 'SELECT Users.Name'

-- This is the same as looping through each section, concatenating each line.
SELECT @SQL = @SQL + ', MAX(CASE WHEN UserSectionRights.SectionID = ' + Sections.SectionID + ' THEN UserSectionRights.Value ELSE 0 END) AS ' + Sections.Name
FROM Sections
ORDER BY Sections.Name

SET @SQL = @SQL + '
FROM Users
INNER JOIN UserSectionRights ON Users.UserID = UserSectionRights.UserID
GROUP BY Users.UserID, Users.Name'

EXECUTE (@SQL)
So it might generate something like this:

Code:
SELECT Users.Name
, MAX(CASE WHEN UserSectionRights.SectionID = 1 THEN UserSectionRights.Value ELSE 0 END) AS Section 1
, MAX(CASE WHEN UserSectionRights.SectionID = 2 THEN UserSectionRights.Value ELSE 0 END) AS Section 2
, MAX(CASE WHEN UserSectionRights.SectionID = 3 THEN UserSectionRights.Value ELSE 0 END) AS Section 3
FROM Users
INNER JOIN UserSectionRights ON Users.UserID = UserSectionRights.UserID
GROUP BY Users.UserID, Users.Name
Hope this helps.
magua is offline  
 

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76