简体   繁体   中英

Sum based on row number in SQL

Sorry if the title is inappropriate.Let me explain what am trying to do. I have a calender table which i used for fetching data from my sales table. Here is the resulting table.

SoldQty  StandardDate   RowNum
1        2013-10-30     1
5        2013-10-31     2
1        2013-10-30     3
1        2013-10-31     4
4        2013-10-30     5
1        2013-10-31     6
2        2013-10-31     8
1        2013-10-31     9

What i need is the sum based on row number i need the sum of values of first three rows,then the next three and the last 3. Is there a way to achieve this or should i insert this into a temp table and write select statements based on the row number. Thanks in advance

Update:

Expected output should be like this

Sold 
1.4   ->(sum of 1 to 3)*.20
1.8   ->(sum of 4 to 6)*.30 
2     ->(sum of 7 to 9)*.50 

or just

  Sold 
  5.2 -> sum of all the above values

When you need to group result, you must have a group to do that ;-).

For you case you can use the column RowNum . The trick is to translate the sequence into grouped values.

1 - 0
2 - 0
3 - 0

4 - 1
5 - 1
6 - 1

This is quite easy to do with math. (RowNum -1 ) / 3 will do the trick.

So the query for you is

select count(SoldQty) from table group by (RowNum -1 ) / 3

The query below will give you the sums by categories you described:

DECLARE @maxRowNumber INT

SELECT @maxRowNumber = MAX(RowNum)
FROM   Data;

WITH Sums(Description, Total)
     AS (SELECT 'Sum of 1 to 3',
                SUM(SoldQty) * .20
         FROM   Data
         WHERE  RowNum <= 3
         UNION ALL
         SELECT 'Sum of 4 to 6',
                SUM(SoldQty) * .30
         FROM   Data
         WHERE  RowNum >= 4
                AND RowNum <= 6
         UNION ALL
         SELECT 'Sum of '
                + CAST(@maxRowNumber-3 AS VARCHAR(10))
                + ' to '
                + CAST(@maxRowNumber AS VARCHAR(10)),
                SUM(SoldQty) * .30
         FROM   Data
         WHERE  RowNum >= @maxRowNumber - 3)
SELECT *
FROM   Sums 

To get the sum of the values from categories, replace * with SUM(Total)

The final query you are looking for is:

select 
   sum( SoldQty * case ( ( [numrow]-1) /3) 
                  when 0 then 0.2 
                  when 1 then 0.3 
                  when 2 then 0.5 
                  end ) as result
   from [yourCalendarTable]

Notice than ( [numrow]-1) /3 is an integer but a decimal because you operate with integers.

Take count(*) and store it in one int variable. then use the method "danihp" said above. OR Add one more column with identity take Max(identity_field) then use the same method.

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