简体   繁体   中英

Calculated rows in SQL

I have a table with a column called metrics that have different possible metrics as:

Metric  Value
--------------
A       100
B       200
C       300

I want to derive another table from this base table that may have rows like:

Metric  Value
--------------
A       100
B       200
C       300
C/A     3
B/A     2

Basically keeping original rows as is + adding some new rows based on existing value's combinations.

One way I could think of doing this is: 1. Pivot the data 2. Put it in some temp table or CTE 3. Select all existing metric columns + New calculated columns I need 4. unpivot the output of the last step

Is there a better way to achieve this with SQL? Or perhaps any other possible way? Also, redshift doesn't support Pivot function, is there a workaround for that in addition to using Case Statements?

You could join the table with itself and apply the operation on the pairs of metrics you like. And UNION ALL the table as it is to include the original metrics.

One possibility for your example would be (assuming Postgres):

SELECT metric,
       value
       FROM metrics
UNION ALL
SELECT concat(m1.metric, '/', m2.metric),
       m1.value / m2.value
       FROM metrics m1
            CROSS JOIN metrics m2
       WHERE (m1.metric,
              m2.metric) IN (('C',
                              'A'),
                             ('B',
                              'A'));

SQL Fiddle

Of course this could be extended to ternary, ... operations by adding another join and several different operations by adding other queries and UNION ing them.

select 
case when x1.metric = x2.metric 
    then x1.metric 
else x1.metric || ' / ' || x2.metric end,
case when x1.metric = x2.metric 
    then x1.value 
else x1.value / x2.value end

from mytable x1
join mytable x2
  on x1.metric = x2.metric or x2.metric = 'A'

This is one way to do it, and its using purely standard sql. Note however, that different RDMBS software have different levels of standards-conformance, and may not support some of the features used here. Specifically, string concatenation operator || isn't implemented in all databases. Some databases use the function concat or + instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM