Click here to Skip to main content
15,891,943 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a sql query group by query like this.
SQL
SELECT cusName, cellPerBlock, SUM(block), SUM(cell) FROM [tbCus] GROUP BY cusName, cellPerBlock

But I need a query that will perform like the following code.
C#
if(cell >= cellPerBlock)
{
      block += cell / cellPerBlock;
      cell %= cellPerBlock;
}
while (cell < 0)
{
     cell += cellPerBlock;
     block--;
} 

Thank's In advance.
Posted
Comments
Kumar Pankaj Verma 7-Jan-15 12:33pm    
Better way to achive this to create a use defined function and call that in query because you are using loop in the code.
Kschuler 7-Jan-15 16:06pm    
The logic you've posted is a bit confusing. Could you include a few examples of data and how you would want them to calculate?

1 solution

Umm maybe something like...
SQL
SELECT

    cusName,
    cellPerBlock,
    case when cell >= cellPerBlock then block + (cell / cellPerBlock) when cell < 0 then block - ((floor((cell * -1) / cellPerBlock))*1) else block end 'block',
    case when cell >= cellPerBlock then floor(cell / cellPerBlock) when cell < 0 then cell + (cellPerBlock * ((floor((cell * -1) / cellPerBlock))*1)) else cell end 'cell'

FROM [tbCus]

or if you need the group by clause, use a nested query
SQL
FROM
(
    SELECT cusName, cellPerBlock, SUM(block) 'block', SUM(cell) 'cell' FROM [tbCus] GROUP BY cusName, cellPerBlock
)

Since you said a query, I kept it as one statement.

I replaced the while loop with what I think a mathematical equivalent is. (I had to make some assumptions about your data)

So for the while loop
C#
while (cell < 0)
{
     cell += cellPerBlock;
     block--;
}

cell = -10
cellPerBlock = 2
block = 10

Result: cell = 0, block = 5

In the query,
SQL
when cell < 0 then cell + ((cellPerBlock * ((floor((cell * -1)/ cellPerBlock))*1)) else cell end 'cell'

cell = -10 + (2 * ((-10*-1) % 2)*1) = 0
SQL
when cell < 0 then block - ((floor((cell * -1)/cellPerBlock))*1) else block end 'block'

block = 10 - (((-10*-1) % 2)*1) = 5

The *1 at the end is to handle the event when your while loop would have ran once but my formula would deliver a quotient of 0. I think my brackets and maths is right, not tested it.
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900