Home > Net >  How to pivot a table using SQL - Unrecognized value
How to pivot a table using SQL - Unrecognized value

Time:07-18

I'm trying to pivot a table using SQL. My table looks like this:

ID import status
cust1 100 Authorized
cust1 10 Authorized
cust2 20 Rejected
cust3 15 Authorized
cust3 70 Rejected

And the expected outcome is this one:

ID Authorized Rejected
cust1 110 null
cust2 null 20
cust3 15 70

I'm using the following code, but for some reason I can't make it work:

select id_account,[Authorized],[Rejected]

from 
(select id_account, import, status_name as status,
  from `mytable` t7
  where transaction_type_code in (6,9) and authorization_date > '2022-06-01' and authorization_date <= '2022-06-30') 
  as src

pivot
  (sum(import) for status in ([Authorized], [Rejected])) as pvt

The error I get is that it doesn't recognize [Authorized], but it's one of the options that I have on the status_name column. More specifically, the error says: Unrecognized name: Authorized at [17:26]

Does anybody know why I might be getting this error?

CodePudding user response:

You need to provide pivot columns as string literals. Consider below query.

SELECT * FROM (
  SELECT ID, import, status FROM mytable
) PIVOT (SUM(import) FOR status in ('Authorized', 'Rejected'));

enter image description here

  • Related