Question

For example, my table data looks like this:

       ID  intValue  date
       1   5         1/1/1
       1   10        22/22/22

What I want to do is multiply the intValue column by 5, 10, and 15 for each instance of intValue.

So my result set would like like:

       ID  intValue  date
       1   25         1/1/1
       1   50         1/1/1
       1   75         1/1/1
       1   50         22/22/22
       1   100        22/22/22
       1   150        22/22/22

How would I get a result set like this?

SOLUTION

qxg's answer below most accurately answered how to best handle the question above. Another way to manipulate the data, and the method by which I used it was:

SELECT CASE WHEN CrossTable.Value = 5 THEN 'By Five!' 
WHEN CrossTable.Value = 10 Then 'By Ten!'
WHEN CrossTable.Value = 15 Then 'By Fifteen!' END AS ByWhat,
CrossTable.Value As Base Value,
intValue * CrossTable.Value
FROM table1
CROSS JOIN (VALUES (5), (10), (15)) CrossTAble(Value)
Was it helpful?

Solution

Leverage CROSS JOIN and Values

SELECT ID, table1.intValue * Val.N, date
FROM table1
CROSS JOIN (VALUES (5), (10), (15)) Val(N)

OTHER TIPS

SELECT A.ID, A.intValue*5*B.number intValue, A.[date]
FROM YourTable A
CROSS JOIN (SELECT *
            FROM master.dbo.spt_values
            WHERE type = 'P'
            AND number BETWEEN 1 AND 3) B

This solution only uses a single union, rather than unioning the table to itself:

WITH    numbers
          AS ( SELECT   5 AS n
               UNION ALL
               SELECT   n + 5
               FROM     numbers
               WHERE    n + 5 <= 15
             )
    SELECT  id ,
            intValue + n AS intValue ,
            date
    FROM    numbers
            CROSS JOIN your_table

This solution is limited to providing sequences that can be expressed mathematically. However, it's advantage is that with only a little adaptation the number of values provided at run-time via a variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top