-2

Edited: I've a table of bill receipt as follows. Here fee_title count is unknown. there can be multiple title more than 3 title

|  rec_no|   fee_title  | amount|
---------------------------------
|     1  |   monthly fee|    200|
|     1  |     tie fee  |    100|
|     2  |  computer fee|    150|
|     3  |   monthly fee|    200|
---------------------------------

I want to show above receipt as

|  rec_no|   monthly fee| tie fee| computer fee |
-------------------------------------------------
|     1  |     200      |    100|         0     |
|     2  |       0      |      0|        150    |
|     3  |     200      |    0  |          0    |
-------------------------------------------------

I found to solve this problem I've to use PIVOT but I don't know how to use it. Anyone can help me

  • 2
    Does this answer your question? [Understanding PIVOT function in T-SQL](https://stackoverflow.com/questions/10428993/understanding-pivot-function-in-t-sql) – Isaac Jan 27 '20 at 03:30

1 Answers1

1

This is more easily achieved using conditional aggregation:

SELECT rec_no,
       SUM(CASE WHEN fee_title = 'monthly fee' THEN amount ELSE 0 END) AS [monthly fee],
       SUM(CASE WHEN fee_title = 'tie fee' THEN amount ELSE 0 END) AS [tie fee],
       SUM(CASE WHEN fee_title = 'computer fee' THEN amount ELSE 0 END) AS [computer fee]
FROM receipts
GROUP BY rec_no

But you can also write as a PIVOT:

SELECT rec_no,
       COALESCE([monthly fee], 0) AS [monthly fee],
       COALESCE([tie fee], 0) AS [tie fee],
       COALESCE([computer fee], 0) AS [computer fee]
FROM receipts
PIVOT (
  SUM(amount)
  FOR fee_title IN ([monthly fee], [tie fee], [computer fee])
) AS p

In both cases the output is:

rec_no  monthly fee     tie fee     computer fee
1       200             100         0
2       0               0           150
3       200             0           0

Demo on SQLFiddle

Nick
  • 138,499
  • 22
  • 57
  • 95
  • what if no.of fee_title is unknown? –  Jan 27 '20 at 03:31
  • You would need to make a dynamic pivot as described [here](https://stackoverflow.com/questions/10428993/understanding-pivot-function-in-t-sql) – Nick Jan 27 '20 at 03:33