Skip to content Skip to sidebar Skip to footer

Use Select Or Pl Sql To Transpose

I have a select query in MySQL shown below: This query executes and produces results in the form of a table Current | Past1 | Past2 | Past 3 | Past4 200 600 800

Solution 1:

One way to do that is a union:

WITH YourWith as (
    select value1, value2, value3, ...
    from YourTable
)
select name ='Current', value1 from YourWith
unionallselect name ='Past1', value2 from YourWith
unionallselect name ='Past2', value3 from YourWith
unionall
...

Solution 2:

I'd do your query in a different way so that the data comes out the way you want.

  1. Create a table (e.g. Ages) to define your intervals (name, lowerBound, upperBound) If you want get fancy, all you need is the "border values" and the corresponding upperBound can be constructed with a self-join.
  2. Then use this table and join it to your "facts" table:

(Can't seem to figure out how to properly format the following statemen to show up as code without this line ...)

SELECT name, COUNT(*)
FROM cpt-prod JOIN Ages on cpt_originated 
    between Subdate(now - upperBound) And Subdate (now - lowerBound)
GROUPBY name

Depending on your needs and dbms, you may be able to define your Ages table in the actual SQL statement. (AFAIK, this can't be done in Oracle, but maybe someone can add a comment on how to do this in MySQL).

Post a Comment for "Use Select Or Pl Sql To Transpose"