Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
tech1
Starting Member
49 Posts |
Posted - 2010-06-16 : 10:43:33
|
| Trying combine multiple tables based on this query:headings:Company NameContact NameLast login dateNo of times logged inPages viewedNo. of downloadsNo of requests submittedAnything relating to "Company" is in the - company table (companyID)Everything else is in the "Audit" table.The Audit table has an auditTypeID (AuditType being login, pages viewed, downloads, requests submitted)the AuditTable has userIDthe User table has UserID and companyIDso for a company, and for each user within that company, I want the above details for that user for a given companyIDhow would I create this query? |
|
|
tech1
Starting Member
49 Posts |
Posted - 2010-06-16 : 11:34:33
|
this kind of worksquote: SELECT comp.CompanyName, u.ContactName, (SELECT TOP 1 a0.createdOn FROM Audit a0 WHERE a0.userId = u.userId AND a0.auditTypeId = 0 ORDER BY a0.createdOn DESC) AS 'LastLogonDate', (SELECT COUNT(a1.[auditID]) FROM Audit a1 WHERE a1.auditTypeId = 0 AND a1.userId = u.UserID) AS 'NoOfTimesLoggedIn', (SELECT COUNT(a2.[auditID]) FROM Audit a2 WHERE a2.auditTypeId = 2 AND a2.userId = u.userId) AS 'PagesViewed', (SELECT COUNT(a3.[auditID]) FROM Audit a3 WHERE a3.auditTypeId = 1 AND a3.userId = u.userId) AS 'NoOfDownloads', (SELECT COUNT(a4.[auditID]) FROM Audit a4 WHERE a4.auditTypeId = 3 AND a4.userId = u.userId) AS 'NoOfRequestSubmitted' FROM [User] u INNER JOIN Company comp ON comp.companyId = u.companyId INNER JOIN Audit a ON a.userId = u.userId WHERE comp.companyId = @paramHere
except, shows ALOT of duplicate records but the correct values I think - something im doing wrong here but no idea what, doing a DISTINCT does work correctly but the query I am doing wrong somewhere |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2010-06-18 : 12:29:12
|
| [code]SELECT COUNT(CASE WHEN a1.auditTypeId = 0 THEN a1.[auditID] ELSE NULL END) AS [NoOfTimesLoggedIn],COUNT(CASE WHEN a1.auditTypeId = 2 THEN a1.[auditID] ELSE NULL END) AS [PagesViewed],COUNT(CASE WHEN a1.auditTypeId = 1 THEN a1.[auditID] ELSE NULL END) AS [NoOfDownloads],COUNT(CASE WHEN a4.auditTypeId = 3 THEN a1.[auditID] ELSE NULL END) AS [NoOfRequestSubmitted],u1.createdOn AS LastLogonDateFROM [User] uINNER JOIN Company comp ONcomp.companyId = u.companyIdINNER JOIN Audit a ONa.userId = u.userIdOUTER APPLY (SELECT TOP 1 a0.createdOn FROM Audit a0 WHEREa0.userId = u.userId AND a0.auditTypeId = 0 ORDER BY a0.createdOn DESC)u1WHERE comp.companyId = @paramHere[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|
|
|
|