Return Table from SQL Query - sql

I have 3 tables in an SQL Server 2008 database. The first table contains users names, the second contains privileges and the last links the first two tables:
USERS (ID integer, NAME varchar(20));
PRIVS (ID integer, NAME varchar(50));
USERS_PRIVS (USERID integer, PRIVID integer);
For example, the USERS table has the following:
1, Adam
2, Benjamin
3, Chris
The PRIVS table has:
1, Add Invoice
2, Edit Invoice
3, Delete Invoice
The USERS_PRIVS table has:
1, 1
1, 2
1, 3
2, 1
2, 2
3, 1
I am looking for a way to create an SQL query that would return something like the following:
Add Invoice Edit Invoice Delete Invoice
Adam Y Y Y
Benjamin Y Y N
Chris Y N N
Is this possible using the pivot function?

SELECT Name, [Add Invoice],[Edit Invoice],[Delete Invoice] FROM
(SELECT U.Name AS Name, P.Name AS PrivName FROM USERS_PRIVS UP
INNER JOIN Users U ON UP.UserID = U.id
INNER JOIN Privs P ON UP.PrivID = P.id) SB
PIVOT(
count(SB.PrivName)
FOR SB.PrivName in ([Add Invoice],[edit Invoice],[Delete Invoice])) AS Results
EDIT 1:
You will have to use some dynamic sql then.
DECLARE #query AS NVARCHAR(MAX);
DECLARE #privColumnNames AS NVARCHAR(MAX);
select #privColumnNames = STUFF((SELECT distinct ',' + QUOTENAME(Name)
FROM PRIVS FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '');
SELECT #query =
'SELECT *
FROM
(SELECT U.Name AS Name, P.Name AS PrivName FROM USERS_PRIVS UP
INNER JOIN Users U ON UP.UserID = U.id
INNER JOIN Privs P ON UP.PrivID = P.id) SB
PIVOT(
count(SB.PrivName)
FOR SB.PrivName in ( ' + #privColumnNames + ' )) AS Results ';
execute(#query);
I borrowed the XML stuff from here Dynamic Pivot Columns in SQL Server

Try this:
select
name,
CASE [1] WHEN 1 THEN 'Y' ELSE 'N' END as 'Add Invoice',
CASE [2] WHEN 1 THEN 'Y' ELSE 'N' END as 'Edit Invoice',
CASE [3] WHEN 1 THEN 'Y' ELSE 'N' END as 'Delete Invoice'
from
(select name, userId, privid, 1 temp from users_privs join users on id = userid) as sourceTable
pivot( min(temp) for privid in ([1], [2], [3])) as pivotTable

Here's a Demo on SqlFiddle.
with cl
as (
select u.NAME , case when p.ID = 1 then 'Y' else 'N' end 'Add Invoice',
case when p.ID = 2 then 'Y' else 'N' end 'Edit Invoice',
case when p.ID = 3 then 'Y' else 'N' end 'Delete Invoice'
from USERS u inner join USERS_PRIVS up on u.ID = up.USERID
inner join PRIVS p on up.PRIVID = p.ID
)
select NAME, MAX([Add Invoice]) 'Add Invoice',
MAX([Edit Invoice]) 'Edit Invoice',
MAX([Delete Invoice]) 'elete Invoice'
from cl
group by NAME
Here's a Demo on SqlFiddle.
select NAME , case when [Add Invoice] = 1 then 'Y' else 'N' end 'Add Invoice',
case when [Edit Invoice] = 1 then 'Y' else 'N' end 'Edit Invoice',
case when [Delete Invoice] = 1 then 'Y' else 'N' end 'Delete Invoice'
from (
select u.NAME, p.NAME as pname
from USERS u inner join USERS_PRIVS up on u.ID = up.USERID
inner join PRIVS p on up.PRIVID = p.ID
) p
pivot( count(pname) for pname in ([Add Invoice], [Edit Invoice], [Delete Invoice])) as pvt

Related

SQL query to conditionally select a field value

I have an SQL query that joins 3 tables to return me the required data. The query is as follows:
SELECT (s.user_created,
u.first_name,
u.last_name,
u.email,
s.school_name,
p.plan_name,
substring( a.message, 11), u.phone1)
FROM cb_school s
inner join ugrp_user u
on s.user_created = u.user_id
inner join cb_plan p
on s.current_plan = p.plan_id
inner join audit a
on u.user_id = a.user_id
where s.type = 'sample'
and a.module_short = 'sample-user'
and s.created_time > current_timestamp - interval '10 day';
The query works fine if all the attributes are present. Now for few of my rows, the following value would be a.module_short = 'sample-user' missing. But since I have included it as an AND condition, those rows will not be returned. I am trying to return an empty string for that field if it is present, else the value as per my current query. Is there any way to achieve this.
Think you could possibly use a CASE WHEN statement, like this:
SELECT CASE WHEN a.module_short = 'sample-user' THEN a.module_short
ELSE '' END AS a.module_short
FROM TableA
you can use COALESCE it returns the first not null.
SELECT COALESCE(a.module_short,'')
FROM TableA AS a
SELECT (s.user_created,
u.first_name,
u.last_name,
u.email,
s.school_name,
p.plan_name,
substring( a.message, 11), u.phone1)
FROM cb_school s
INNER JOIN ugrp_user u
ON s.user_created = u.user_id
INNER JOIN cb_plan p
ON s.current_plan = p.plan_id
INNER JOIN audit a
ON u.user_id = a.user_id
AND a.module_short = 'sample-user'
WHERE s.type = 'sample'
AND s.created_time > current_timestamp - interval '10 day';
You want to show all users that have at least one module_short.
If the module_short contains 'sample-user' then it should show it, else it should show NULL as module_short. You only want 1 row per user, even if it has multiple module_shorts.
You can use a CTE, ROW_NUMBER() and the CASE clause for this question.
Example Question
I have 3 tables.
Users: Users with an ID
Modules: Modules with an ID
UserModules: The link between users and modules. You user can have multiple models.
I need a query that returns me all users that have at least 1 module with 2 columns UserName and ModuleName.
I only one 1 row for each user. The ModuleName should only display SQL if the user has that module. Else it should display no module.
Example Tables:
Users:
id name
1 Manuel
2 John
3 Doe
Modules:
id module
1 StackOverflow
2 SQL
3 StackExchange
4 SomethingElse
UserModules:
id module_id user_id
1 1 2
2 1 3
4 2 2
5 2 3
6 3 1
7 3 3
8 4 1
9 4 3
Example Query:
with CTE as (
select
u.name as UserName
, CASE
WHEN m.module = 'SQL' THEN 'SQL' ELSE NULL END as ModuleName
, ROW_NUMBER() OVER(PARTITION BY u.id
ORDER BY (CASE
WHEN m.module = 'SQL' THEN 'Ja' ELSE NULL END) DESC) as rn
from UserModules as um
inner join Users as u
on um.user_id = u.id
inner join Modules as m
on um.module_id = m.id
)
select UserName, ModuleName from CTE
where rn = 1
Example Result:
UserName ModuleName
Manuel NULL
John SQL
Doe SQL
Your query would look like this:
with UsersWithRownumbersBasedOnModule_short as (
SELECT s.user_created,
u.first_name,
u.last_name,
u.email,
s.school_name,
p.plan_name,
substring( a.message, 11),
u.phone1)
CASE
WHEN a.module_short = 'sample-user'
THEN a.module_short
ELSE NULL
END AS ModuleShort
ROW_NUMBER() OVER(PARTITION BY u.user_id ORDER BY (
CASE
WHEN a.module_short = 'sample-user'
THEN a.module_short
ELSE NULL
END) DESC) as rn
FROM cb_school s
inner join ugrp_user u
on s.user_created = u.user_id
inner join cb_plan p
on s.current_plan = p.plan_id
inner join audit a
on u.user_id = a.user_id
where s.type = 'sample'
and s.created_time > current_timestamp - interval '10 day';)
select * from UsersWithRownumbersBasedOnModule_short
where rn = 1
PS: I removed a lose bracket after SELECT and your SUBSTRING() is missing 1 parameter, it needs 3.

How to get amount of records of a specific ID in a database?

I want to check which users have the most records in a database. So every user has a specific Id, and that Id is used as a reference in a few tables.
There are a few tables that contain a column UserId, like the table Exams, Answers, Questions, Classes, etc. Is it possible to count all the records with a specific UserId in all those tables?
;with cte as (
select rowsCount = count(*) from A where UserId = 1
union all
select rowsCount = count(*) from B where UserId = 1
union all
select rowsCount = count(*) from C where UserId = 1
)
select sum(rowsCount) from cte
I would do it in this way:
With AllRecords AS
(
SELECT TableName = 'Exams'
FROM dbo.Exams
WHERE UserId = #YouruserID
UNION ALL
SELECT TableName = 'Answers'
FROM dbo.Answers
WHERE UserId = #YouruserID
UNION ALL
SELECT TableName = 'Questions'
FROM dbo.Questions
WHERE UserId = #YouruserID
UNION ALL
SELECT TableName = 'Classes'
FROM dbo.Classes
WHERE UserId = #YouruserID
)
SELECT COUNT(*) FROM AllRecords
The table-name is not needed if you just want the count, it's just for the case that you want to know the source.
Try like this,
SELECT Count(E.ID) + Count(A.ID) + Count(Q.ID) + Count(C.ID) AS SumofAllCount
FROM dbo.Exams E
LEFT JOIN dbo.Answers A ON A.UserId = E.UserId
LEFT JOIN dbo.Questions Q ON Q.UserId = E.UserId
LEFT JOIN dbo.Classes C ON C.UserId = E.UserId
WHERE E.UserId = #YouruserID
GROUP BY E.UserId

SQL Dynamic Pivot Query

I need help with a pivot table if possible. Not sure it can be done. Below is my example.
Questions
Answers
User Answers
Answer Pivot
Thanks For any help.
I have attached a screenshot of db results with the pivot working . The code below pivot as it should and that works fine. If you can look at the column "Subject has exp..." I would like the column repeated three times, The heading is the question, But I also would like each possible answer to shown with the question as well.
Thank Again!
Thansk Again.
Here Is a Sample of the Code:
DECLARE #columns VARCHAR(MAX)
SELECT #columns = COALESCE(#columns + ','+QUOTENAME([QuestionText]),QUOTENAME([QuestionText]))
FROM SchemaWema.vts_vwSurvey INNER JOIN
Question ON SchemaWema.vts_vwSurvey.SurveyID = SchemaWema.vts_vwQuestion.SurveyID
WHERE SchemaWema.vts_vwSurvey.DecisionSetId = 598 AND SchemaWema.vts_vwSurvey.FormType = 1
Set #columns = REPLACE(#columns, '[]', '[No Name Given]')
DECLARE #sql NVARCHAR(MAX)=N' SELECT * FROM
(
SELECT Project.PROJECTNAME, Project.ID,
Sites.PROJECTSTUDYSITENUMBER, Sites.PROJECTSTUDYSITENAME,
Study.PROJECTSTUDYNAME, Study.PROJECTSTUDYNUMBER,
Survey.SurveyID, Question.QuestionID, Cases.SITEID, Cases.EVENTDATE,
Cases.SUBJNO, Cases.EventType, Cases.TriggerEvent,
Cases.DecisionSetID, Cases.PanelID, Cases.RECORDSTATUS,
Project.PROJECTSPONSOR, VoterAnswers.AnswerID, VoterAnswers.VoterID,
VoterAnswers.AnswerText AS FreeTypedAnswers, Voter.VoteDate, Users.SHOWNNAME, Panel.PANELNAME, Sites.COUNTRY,
Cases.VERSIONID, cases.CSID, cases.CASENUMBER,Cases.CASEDATEUPDATED AS LASTUPDATED,
Cases.DECISIONSETNAME,
Question.QuestionText,
CASE
WHEN
CAST(VoterAnswers.AnswerText AS VARCHAR(MAX)) IS NULL OR CAST(VoterAnswers.AnswerText AS VARCHAR(MAX)) = ''''
THEN
Answer.AnswerText
ELSE
CAST(Answer.AnswerText AS VARCHAR(MAX))
END AS AnswerText
FROM
(
SELECT a.ID, a.STUDYID, a.SITEID, a.CSID, a.VERSIONID, a.CASENUMBER, a.CASEINITIALS, a.EVENTDATE, a.CASEDETAILSFILE, a.CASEDETAILSFILEVERSION,
a.CASESTATUS, a.RECORDSTATUS, a.CASEDATEUPDATED, a.PROJECTDATEUPDATED, a.PanelID, a.DecisionSetID, a.SUBJNO, a.EventType, a.TriggerEvent,
a.Priority, a.id1, a.id2, a.dateid, a.dateiddt1, a.dateiddt2, a.extratext1, a.extratext2, SchemaWema.PROJECTPANELDECISIONSETVIEW.DECISIONSETNAME
FROM SchemaWema.PROJECTCASE AS a LEFT OUTER JOIN
SchemaWema.PROJECTPANELDECISIONSETVIEW ON a.DecisionSetID = SchemaWema.PROJECTPANELDECISIONSETVIEW.DECISIONSETID
WHERE (a.CASEDATEUPDATED =
(SELECT MAX(CASEDATEUPDATED) AS Expr1
FROM SchemaWema.PROJECTCASE AS b
WHERE (a.ID = PROJECTID) AND (a.CSID = CASEID) AND (a.VERSIONID = VERSIONID) )) AND (a.RECORDSTATUS <> ''D'')
)Cases
LEFT OUTER JOIN
(
SELECT PROJECTID, PROJECTNAME, PROJECTSPONSOR
FROM SchemaWema.PROJECT AS a
WHERE (PROJECTDATEUPDATED =
(SELECT MAX(PROJECTDATEUPDATED) AS Expr1
FROM SchemaWema.PROJECT AS b
WHERE (a.ID = PROJECTID))) AND (RECORDSTATUS <> ''D'')
) Project on
Project.ID = Cases.ID
LEFT OUTER JOIN
(
SELECT DISTINCT a.ID, a.STUDYID, a.SITEID, a.PROJECTSTUDYSITENAME, a.PROJECTSTUDYSITENUMBER, SchemaWema.PROJECTSTUDYVIEW.PROJECTSTUDYNAME, a.COUNTRY
FROM SchemaWema.PROJECTSTUDYSITE AS a INNER JOIN
SchemaWema.PROJECTVIEW ON a.ID = SchemaWema.PROJECTVIEW.ID INNER JOIN
SchemaWema.PROJECTSTUDYVIEW ON a.ID = SchemaWema.PROJECTSTUDYVIEW.ID AND
a.STUDYID = SchemaWema.PROJECTSTUDYVIEW.STUDYID
WHERE (a.PROJECTSTUDYSITEDATEUPDATED =
(SELECT MAX(PROJECTSTUDYSITEDATEUPDATED) AS Expr1
FROM SchemaWema.PROJECTSTUDYSITE AS b
WHERE (a.ID = PROJECTID) AND (a.STUDYID = STUDYID) AND (a.SITEID = SITEID))) AND (a.RECORDSTATUS <> ''D'')
)Sites on
Cases.SITEID = Sites.SITEID
LEFT OUTER JOIN
(
SELECT DISTINCT PROJECTID, STUDYID, PROJECTSTUDYNAME, PROJECTSTUDYNUMBER, PROJECTSTUDYDESCRIPTION
FROM SchemaWema.PROJECTSTUDY AS a
WHERE (PROJECTSTUDYDATEUPDATED =
(SELECT MAX(PROJECTSTUDYDATEUPDATED) AS Expr1
FROM SchemaWema.PROJECTSTUDY AS b
WHERE (a.ID = PROJECTID) AND (ISNULL(a.STUDYID, ''0'') = ISNULL(STUDYID, ''0'')))) AND (RECORDSTATUS <> ''D'')
)Study on
Study.STUDYID = Cases.STUDYID
inner join
(
SELECT VoterID, UID, SurveyID, ContextUserName, VoteDate, StartDate, IPSource, Validated, ResumeUID, ResumeAtPageNumber, ProgressSaveDate,
ResumeQuestionNumber, ResumeHighestPageNumber, LanguageCode, SurveyStatus, VoteAcceptRejectDate, CaseID, VersionID, PdfFileName, voterSurveyStatus,
dateupdated, recordstatus, modifiedby, changereason
FROM SchemaWema.vts_tbVoter AS a
WHERE (dateupdated =
(SELECT MAX(dateupdated) AS Expr1
FROM SchemaWema.vts_tbVoter AS b
WHERE (a.VoterID = VoterID) AND (a.SurveyID = SurveyID) AND (a.CSID = CaseID) AND (a.VersionID = VersionID)))
) Voter on
Voter.CSID = Cases.CSID
AND Voter.VersionID = Cases.VersionID
Inner Join
(
SELECT DISTINCT SurveyID, DecisionSetId, FormType
FROM SchemaWema.vts_tbSurvey AS a
WHERE (dateupdated =
(SELECT MAX(dateupdated) AS Expr1
FROM SchemaWema.vts_tbSurvey AS b
WHERE (a.SurveyID = SurveyID))) AND (recordstatus <> ''D'')
) Survey on
Survey.SurveyID = Voter.SurveyID
inner Join
(
SELECT DISTINCT
VoterID, AnswerID, SectionNumber, CAST(AnswerText AS varchar(MAX)) AnswerText, SurveyID, CaseID, versionID
FROM SchemaWema.vts_tbVoterAnswers AS a
WHERE (dateupdated =
(SELECT MAX(dateupdated) AS Expr1
FROM SchemaWema.vts_tbVoterAnswers AS b
WHERE (a.VoterID = VoterID) AND (a.AnswerID = AnswerID) AND (a.SectionNumber = SectionNumber) AND (a.SurveyID = SurveyID) AND (a.CSID = CaseID) AND
(a.versionID = versionID))) AND (recordstatus <> ''D'')
)VoterAnswers on
VoterAnswers.SurveyID = Survey.SurveyID
AND VoterAnswers.CSID = Voter.CSID
AND Voter.VoterID = VoterAnswers.VoterID
AND VoterAnswers.versionID = Voter.versionID
AND VoterAnswers.SurveyID = Voter.SurveyID
FULL OUTER JOIN
(
select DISTINCT a.USERID, a.USERNAME, a.FIRSTNAME, a.LASTNAME, a.SHOWNNAME
from SchemaWema.users as a
WHERE (a.userdateupdated =
(SELECT MAX(b.userdateupdated) AS Expr1
FROM SchemaWema.users AS b
WHERE (a.userID = b.userID) ))
AND (a.RECORDSTATUS <> ''D'')
) Users on
VoterAnswers.VoterID = Users.USERID
AND Voter.VoterID = Users.USERID
inner join
(
SELECT DISTINCT AnswerID, QuestionID, AnswerText FROM SchemaWema.vts_tbAnswer AS a
WHERE (dateupdated =
(SELECT MAX(dateupdated) AS Expr1
FROM SchemaWema.vts_tbAnswer AS b
WHERE (a.AnswerID = AnswerID))) AND (recordstatus <> ''D'')
) Answer on
Answer.AnswerID = VoterAnswers.AnswerID
inner Join
(
SELECT DISTINCT QuestionID,SurveyID, QuestionText
FROM SchemaWema.vts_tbQuestion AS a
WHERE (dateupdated =
(SELECT MAX(dateupdated) AS Expr1
FROM SchemaWema.vts_tbQuestion AS b
WHERE (a.QuestionID = QuestionID))) AND (recordstatus <> ''D'')
) Question on
Answer.QuestionID = Question.QuestionID
AND Question.SurveyID = Survey.SurveyID
AND Question.SurveyID = VoterAnswers.SurveyID
inner join
(
SELECT DIStinct
[PANELID] ,[PANELNAME]
FROM [AdjudicateV3].[Adjudicate].[PROJECTPANELVIEW]
)Panel on
Panel.PANELID = Cases.PanelID
WHERE CASEs.ID = ' + #ID + ' AND Survey.DecisionSetId = '+ DeeSetId +' AND Survey.FormType = '+ #Forms +'
) AS SourceTable
PIVOT
(
MAX(AnswerText)
FOR QuestionText IN ('+#columns+')
) AS PivotTable'
It can be done using a dynamic pivot.
First thing you have to do is build the cols you're going to use for the pivot..
declare #cols varchar(max)
select #cols = Coalesce(#cols + ', ', '') + '[' + q.Question + '(' + a.Question + ')]'
from Questions q
join Answers a on q.ID = a.QuestionID
this will concatenate all of the column headers you want into one string like
[What is your favorite Car Color(Blue)], [What is your favorite Car Color(Red)]
putting the column names inside brackets is important here...
The next step is building your pivot query
declare #sql varchar(max)
set #sql = 'Select [User], ' + #cols + ' from (
select ua.[User], ''X'' as Chosen,
q.Question + ''('' + a.Question + '')'' Answer
from UserAnswers ua
join Answers a On ua.AnswerId = a.ID and ua.QuestionID = a.QuestionID
join Questions q on a.QuestionID = q.ID
) t
pivot (
max(Chosen)
for Answer IN (' + #cols + ')
) p'
exec(#sql)
this will create a subquery with three columns User, Chose, Answer.. user is user name, chosen is just an X for every record, and the Answer, which is what is used to pivot. Answer looks like the column names above without the brackets..
next it pivots the subquery.. and selects the Name and dynamic columns..
SQL Fiddle Example

Get Count in One to Many relation in sql

here is the link of the related question Related question ,
Now i have a query which gives me the company name exactly as i want
QUERY
SELECT CASE WHEN COALESCE(b.totalCoupons, 0) > 3 THEN a.Name +'(Important) '
WHEN IsHighPriority = 1 THEN a.Name +'(High Priority) '
ELSE a.Name +''
END AS CompanyName
FROM Company a
LEFT JOIN
(
SELECT Name, COUNT(*) totalCoupons
FROM Company
GROUP BY Name
) b ON a.name = b.name
Now i want that In the scenario of (important) we are testing that if company have more then 3 coupons then add (Important) infront of Company name but i want to do that if
a company have more then 3 coupons where
RejectProcessed = 0 and ReviewVerify = 0 and isPublish = 0 and ForSupervisor = 0
then i want to add important infront of that particular company name . So , what should i do .
Please feel free to ask if you need any detail .
Thanks in advance
This query solved my problem
SELECT CASE WHEN COALESCE(b.totalCoupons, 0) > 3 THEN company.Name +' (Important) '
WHEN IsHighPriority = 1 THEN company.Name +' (High Priority) '
ELSE company.Name +''
END AS CompanyName , company.id as Companyid
FROM Company company
left JOIN
(
SELECT co.Name as coName, co.id as coid, COUNT(c.id) totalCoupons
FROM Company co, Coupon c
where c.CompanyId = co.id and c.RejectedProcessed = 1 and c.ReviewVerify = 0 and c.isPublish = 0 and c.ForSupervisor = 0
GROUP BY co.Name, co.id
) b ON company.id = b.coid
#user2193861, is Coupon present in left join with company table..?
LEFT JOIN
(
SELECT Name, COUNT(*) totalCoupons
FROM Coupon
GROUP BY Name
) b ON a.name = b.name
Use this..
SELECT CASE WHEN COALESCE(b.totalCoupons, 0) > 3 THEN a.Name +'(Important) '
WHEN IsHighPriority = 1 THEN a.Name +'(High Priority) '
ELSE a.Name +''
END AS CompanyName
FROM Company a
LEFT JOIN
(
SELECT Name, COUNT(*) totalCoupons
FROM Company C
WHERE
EXISTS(
select 1
from coupon P
where P.RejectProcessed = 0 and P.ReviewVerify = 0
and P.isPublish = 0 and P.ForSupervisor = 0
and P.CompanyName = C.Name
)
and in second query..
use WHERE P.RejectProcessed = 0 and P.ReviewVerify = 0
and P.isPublish = 0 and P.ForSupervisor = 0

How to get table-like query result on SQL Server 2005/8?

I have 3 tables:
users (id, name)
currency (id, name)
accounts (id, user_id, currency_id, amount)
And I want to read the data from accounts and present it in table-like view:
owner currency1 currency2 currency3
1 0 0 0
2 10 20 30
3 0 5 10
Where owner is ID of accounts.owner, currency1,2,3 - (SELECT id FROM currency WHERE name = '1',etc)
I can get such result only for one specific ID:
SELECT
SELECT amount FROM accounts WHERE currency = (SELECT id FROM currency WHERE name = 'currency1') AND owner = #user) AS [currency1],
SELECT amount FROM accounts WHERE currency = (SELECT id FROM currency WHERE name = 'currency2') AND owner = #user) AS [currency2],
SELECT amount FROM accounts WHERE currency = (SELECT id FROM currency WHERE name = 'currency2') AND owner = #user) AS [currency2]
Is it possible to get the same result for every object in users table? Without using Reporing Service, etc.
Use a pivot table and dynamic SQL to retrieve the columns
DECLARE #columns VARCHAR(2000)
SELECT #columns = STUFF(( SELECT DISTINCT TOP 100 PERCENT
'],[' + c.name
FROM currency AS c
ORDER BY '],[' + c.name
FOR XML PATH('')
), 1, 2, '') + ']'
DECLARE #query NVARCHAR(4000)
SET #query = N'SELECT UserName, ' + #columns +
'FROM
(SELECT u.Name AS UserName, c.name AS CurrencyName, a.Amount
FROM Accounts AS a WITH(NOLOCK)
JOIN Users u WITH(NOLOCK) ON a.user_id = u.user_id
JOIN Currency c WITH(NOLOCK) ON a.currency_id = c.currency_id
) p
PIVOT
(
SUM (p.Amount)
FOR p.CurrencyName IN
( '+ #columns +')
) AS pvt
ORDER BY UserName'
EXECUTE(#query)
This was tested in SQL Server 2005
Sounds like you want a Pivot table. It will be difficult to do if you have a varying number of rows in currency, but could still be done by using dynamiclly written sql.
Here's a resource from MSDN that explains how to use the pivot table: http://msdn.microsoft.com/en-us/library/ms177410.aspx
SELECT u.name, [1] AS Currency1, [2] AS Currency2, [3] AS Currency3
FROM
(SELECT u.Name AS UserName, c.Currency_ID, a.Amount
FROM Accounts AS a WITH(NOLOCK)
JOIN Users u WITH(NOLOCK) ON a.user_id = u.user_id
) p
PIVOT
(
SUM (p.Amount)
FOR p.Currency_id IN
( [1], [2], [3] )
) AS pvt
ORDER BY pvt.UserName