1

lets say i have a table like this:

type       success    failed
type 1     10         1
type 2     4          0
type 3     5          3

and i want to create a table like this with query

type     state      count
type 1   success    10
type 1   failed     1
type 2   success    4
type 2   failed     0
type 3   success    5
type 3   failed     3

what query should i type to show a table like above?

using colpivot or crosstab?

2
  • Question stilla says "I want to crete a table" you might want to edit that Commented Aug 5, 2021 at 3:56
  • What have you tried ? is your current query showing you any errors ? Commented Aug 5, 2021 at 3:56

2 Answers 2

1

You can try to use UNION ALL

Query 1:

SELECT *
FROM (
  SELECT type,'success' state,success count  FROM T
  UNION ALL
  SELECT type,'failed' ,failed  FROM T
) t
ORDER BY type,state desc

Results:

|   type |   state | count |
|--------|---------|-------|
| type 1 | success |    10 |
| type 1 |  failed |     1 |
| type 2 | success |     4 |
| type 2 |  failed |     0 |
| type 3 | success |     5 |
| type 3 |  failed |     3 |
Sign up to request clarification or add additional context in comments.

Comments

1

Another option is to use a VALUES clause:

select t.type, u.*
from the_table t
  cross join lateral (  
    values ('success', t.success), ('failed', t.failed)
  ) as u(state,count)
order by t.type, u.state;

Online Example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.