Note that there are some explanatory texts on larger screens.

plurals
  1. POCombining multiple rows into one row SQL query
    primarykey
    data
    text
    <p>I have an SQL table below that contains data I need to collate. What I would like to do is combine all data for the ID of 746 contained in column B so that in the Results table column R2 contains the sum of column E when column C is non zero and column R4 contains the sum of column E when column D is none zero. <em>Both sums are then reduced by the percentage displayed in column F,</em> Column R3 will be the sum of column C and column R5 is the sum of column D.</p> <p><strong>Source Data</strong></p> <pre><code>+----+------+-------------+------+------------+----+ | A | B | C | D | E | F | +----+------+-------------+------+------------+----+ | 78 | 746 | 27 | 0 | 592.38 | 50 | | 78 | 746 | 27 | 0 | 592.38 | 50 | | 78 | 746 | 0 | 52.5 | 3178.36 | 50 | | 78 | 746 | 484.25 | 0 | 10616.8450 | | | 78 | 827 | 875 | 0 | 19215 | 50 | | 78 | 827 | 125 | 0 | 2745 | 50 | | 78 | 1078 | 63.59999847 | 0 | 1272 | 50 | +----+------+-------------+------+------------+----+ </code></pre> <p><strong>Results</strong></p> <pre><code>+-----+---------+--------+---------+------+ | R1 | R2 | R3 | R4 | R5 | +-----+---------+--------+---------+------+ | 746 | 5900.80 | 511.25 | 1589.18 | 52.5 | +-----+---------+--------+---------+------+ This script should populate the initial data create table #Test ( A int, B int, C decimal(10,2), D decimal(10,2), E decimal(10,2), F int ) insert into #Test select 78, 746, 27, 0, 0, 50 insert into #Test select 78, 746, 27, 0, 592.38, 50 insert into #Test select 78, 746, 0, 52.5, 3178.36, 50 insert into #Test select 78, 746, 484.25, 0, 10616.8450, 50 insert into #Test select 78, 827, 875, 0, 19215, 50 insert into #Test select 78, 827, 125, 0, 2745, 50 insert into #Test select 78, 1078,63.60, 0, 1272, 50 </code></pre> <p>As this is not something I have done a lot of in SQL server I am feeling a little flummoxed. The area where I think I need to be is subquery but am not exactly sure any help would be fantastic.</p> <p>Thanks</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload