Processit
Processit

Reputation: 55

Pivot sql query with where clause

I have the following script to produce a pivot output, however I am struggling with 2 elements:

1- Having the output showing the output with all userIDs down the left hand side of the output.

2- Putting a where clause in the script which limits the outputs. Tried 100's of options. Any help would be appreciated

SELECT 'invoices.USERID' AS totalvalue,
[1], [2]


FROM

(SELECT invoices.USERID, [total],PAYERCODE
FROM invoices
where invoices.userid = 41
  ) AS SourceTable

PIVOT
(
SUM([total])
FOR PAYERCODE IN ([1], [2])
) AS PivotTable;

enter image description here

So what I would like it to look like is

enter image description here

Any help will be very much appreciated before it messes up my whole weekend.

Upvotes: 1

Views: 3685

Answers (1)

John Cappelletti
John Cappelletti

Reputation: 81970

The Y-Axis was a string 'invoices.USERID'

and remove the WHERE invoices.userid = 41

SELECT USERID AS totalvalue,[1],[2]
FROM 
(SELECT invoices.USERID, [total],PAYERCODE
 FROM invoices
 --where invoices.userid = 41
) AS SourceTable
PIVOT
(
SUM([total])
FOR PAYERCODE IN ([1], [2])
) AS PivotTable;

Upvotes: 1

Related Questions