简体   繁体   中英

How to do some calculations on columns of a SQL Server 2008 R2 table by using a row divide another row on the same column

I would like to do some calculations on some columns of a SQL Server 2008 R2 table.

Example:

Table 1:

  id  value1 value2  value3  valueA  valueB  valueC 
  -------------------------------------------------
  1     0       0     0       5        2        8 
  2     1       1     1       10       12       16 
  3     2       2     2       25       22       20 
  4     5       5     5       30       18       24

I need a table with the results that use the valueA/B/C of value1/2/3 are not 0s to divide the values of value1/2/3 = 0 and get a new table:

  id  value1 value2  value3  valueA     valueB     valueC 
  -------------------------------------------------------
  2     1       1     1       10/5       12/2       16/8 
  3     2       2     2       25/5       22/2       20/8 
  4     5       5     5       30/5       18/2       24/8

I do not know how to design the SQL query.

Thanks

First you create a CTE to get the divide values

Then you perform the division.

See I multiply first for 1.0 to make sure the division generate float value instead a truncated integer

SQL Fiddle Demo

 with divide as (
     select [valueA] dA, [valueB] dB, [valueC] dC
     from formula
     where value1 = 0 AND value2 = 0 AND value3 = 0
 )
 SELECT 
    [value1], [value2], [value3], 
    [valueA] * 1.0 / d.dA, [valueB] * 1.0 / d.dB, [valueC] * 1.0 / d.dC
 FROM formula f, divide d
 WHERE not (value1 = 0 AND value2 = 0 AND value3 = 0)

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