Sum of multiple values of one variable - sql

I want to sum the variable that is holding the value in a loop,
Here's my table:
name | pkey | cinema1~cinema10 | total_QTy | total_sales
aaa | 1 | 100.00 ~ 200.00 | 2 | 300.00
bbb | 2 | 150.00 ~ 145.00 | 3 | 295.00
total_Qty is the sum of the tickets bought in cinema1~cinema10 for name aaa
and I don't know how to do this. I am only getting the last value of counted ticket which is in name bbb cinema10.
Help me please. I'm stuck here.
Here is my code for getting the amount and qty
WHILE ISNULL(#cinema_key, 0) <> 0
BEGIN
SET #amount = 0
SELECT #amount =(SUM(t1.price)), #qty = (count(t1.cnt))
FROM(
SELECT
(ISNULL(SUM(mctrs.price),0) - (ISNULL(SUM(mctrs.lgu_tax_amount),0) + ISNULL(SUM(mctrs.ordinance_1),0) + ISNULL(SUM(mctrs.ordinance_2),0)+ ISNULL(SUM(mctrs.ordinance_3),0) + ISNULL(SUM(mctrs.ordinance_4),0) )) AS 'price',
count(mctrs.[key]) as 'cnt', mctrs.[key] as ckey
FROM
movie_calendar mc
INNER JOIN
movie_database md
ON
mc.movie_key = md.[key] AND mc.screening_start_date = #tdate
INNER JOIN
cinemas c
ON
mc.cinema_key = c.[key] AND c.[key] = #cinema_key
INNER JOIN
movie_calendar_times mct
ON
mct.movie_calendar_key = mc.[key]
LEFT OUTER JOIN
movie_calendar_time_reserved_seats mctrs
ON
mctrs.movie_calendar_time_key = mct.[key]
INNER JOIN
patrons p
ON
mctrs.patron_key = p.[key]
WHERE mctrs.status = 1 AND mctrs.[committed]=1
GROUP BY p.patron_tag,mctrs.price,P.APPLY_LGU_TAX ,P.LGU_TAX_AMOUNT, mctrs.[key]
)t1
SET #buffer = 'UPDATE #temptable SET cinema'+CAST(#count AS VARCHAR)+' = '+CAST(ISNULL(sum(#amount),0) AS VARCHAR)+' WHERE [date] = '''+CAST (#tdate AS VARCHAR)+''''
PRINT (#buffer)
EXEC(#buffer)
insert into #tqty(qty) values(#qty)
DELETE FROM #cinema_list WHERE cinema_key = #cinema_key
SET #cinema_key = NULL
SET #cinema_code = NULL
SELECT TOP 1 #cinema_key = cinema_key, #cinema_code = cinema_code FROM #cinema_list ORDER BY display_order
SET #count = #count + 1
END /*WHILE CINEMA KEY*/
and here's my code in updating the total_Qty and total_sales:
WHILE #count < #cinema_count
BEGIN
SET #count = #count+1.
SET #select = #select+'cinema'+CAST(#count AS VARCHAR)+'+'
END
SET #select = SUBSTRING(#select, 1, LEN(#select) - 1)
SET #buffer = 'UPDATE #temptable SET total_quantity = ' +cast(#qty as varchar) + ', ' + 'total_sales = '+#select
PRINT #buffer
EXEC( #buffer)
Help please :3 Thanks :)

I agree with #Dave Collins that this isn't database design at its greatest however if you want the simple answer, you need to add the existing value to the running total in your update.
Change this:
SET #buffer = 'UPDATE #temptable SET cinema'+CAST(#count AS VARCHAR)+' = '+CAST(ISNULL(sum(#amount),0) AS VARCHAR)+' WHERE [date] = '''+CAST (#tdate AS VARCHAR)+''''
To this:
SET #buffer = 'UPDATE #temptable SET cinema'+CAST(#count AS VARCHAR)+' = ISNULL(cinema,0) + '+CAST(ISNULL(sum(#amount),0) AS VARCHAR)+' WHERE [date] = '''+CAST (#tdate AS VARCHAR)+''''

Related

SQL Query filter with custom field

Below code are use to detect if there exist userid=1 followerid=2 AND userid=2 followerid=1, then the custom column 'bool' will return TRUE.
However, somehow i can't get rid the extra row.
Any better suggestion or recommendations are appreciated. Thank you.
SELECT DISTINCT a.id, a.userid, a.followerid,
CASE WHEN b.userid=a.followerid AND b.followerid=a.userid
THEN 'TRUE' ELSE 'FALSE' END AS bool
FROM tableUserfollow AS a, tableUserfollow AS b
where a.userid=1
tableUserFollow:
id userid followerid
1 1 2
2 3 4
3 1 4
4 5 1
5 2 1
The output result should be:
1 1 2 TRUE
3 1 4 FALSE
instead of this:
1 1 2 FALSE
1 1 2 TRUE
3 1 4 FALSE
If you want to know if the reciprocal relationship is present, then I think the simplest way is using a correlated subquery, left join, or outer apply:
select uf.*, coalesce(flag, 'FALSE') as
from tableUserfollow uf outer apply
(select 'TRUE' as flag
from tableUserfollow uf2
where uf2.userId = uf.followerId and uf2.follwerId = uf.userId
) f;
The join would look like:
select uf.*,
(case when uf2.userId is null then 'FALSE' else 'TRUE' end)
from tableUserfollow uf left join
tableUserfollow uf2
on uf2.userId = uf.followerId and uf2.follwerId = uf.userId
DECLARE #sql AS nvarchar(MAX);
DECLARE #Search AS nvarchar(MAX);
DECLARE #AllFiels Varchar(max);
DECLARE #FixedField Varchar(max);
SET #FixedField=( SELECT
ISNULL(( STUFF(
(
SELECT ', '+(a.value) FROM vwCustomColumns a
WHERE a.Name IN (SELECT items FROM dbo.Split(CustomReports.ReportFixedFields,',') )
FOR XML path('')
)
, 1,1,'')) ,'cR.ContractID [Contract ID]') FixedField
FROM CustomReports WHERE CustomReportId=#CustomReportId )
SET #AllFiels=#FixedField;
SET #sql ='SELECT count(*) OVER() AS Maxcount ,'+#AllFiels+'
FROM vwRequestLatest cR
INNER JOIN MasterUsers ON MasterUsers.UsersId = cR.Addedby
LEFT OUTER JOIN RequestTemplate cte ON cte.ContractTemplateId=cR.RequestTemplateId
LEFT OUTER JOIN CountryMaster co ON co.CountryId=cR.CountryId
ORDER BY
';
IF (#SortColumn = '')
BEGIN
IF (#Direction = 0)
SET #sql =#sql + ' cR.RequestId ASC '
ELSE
SET #sql =#sql + ' cR.RequestId DESC '
END
ELSE IF (#SortColumn = 'Request ID')
BEGIN
IF (#Direction = 0)
SET #sql =#sql + ' cR.RequestId ASC '
ELSE
SET #sql =#sql + ' cR.RequestId DESC '
END
SET #sql =#sql +'OFFSET ( '+CONVERT(VARCHAR(100),#PageNo)+' - 1 ) * '+CONVERT(VARCHAR(100),#RecordsPerPage)+' ROWS FETCH NEXT '+CONVERT(VARCHAR(100),#RecordsPerPage)+' ROWS ONLY'
EXEC(#sql);

SQL IF to Set Parameter Value Within SELECT Statement

EDIT: This problem has been solved using a better method. Rather than using a variable I am concatenating results to get my desired output.
I am trying to get values from several fields from a couple of different tables and that works fine. But I would also like to have a "#Description" which is a concatenation of hard coded text based on existing values for each row.
DECLARE #Description VARCHAR(1000) = ''
SELECT t1.ID
t1.myType
t1.myName
,CASE WHEN
(
t1.aValue1 = 1
AND t1.aValue2 = 1
AND t2.aValue1 = 1
AND t2.aValue2 = 1
)
THEN 'ELIGIBLE'
ELSE 'NOT ELIGIBLE'
END AS 'isEligible'
,#Description
-- Then I'm trying to set the description
/*
IF
(
t1.aValue1 = 2
)
SET #Description = #Description + ' t1.aValue1 is 2'
IF
(
t1.aValue2 = 2
)
SET #Description = #Description + ' t1.aValue2 is 2'
IF
(
t2.aValue1 = 2
)
SET #Description = #Description + ' t2.aValue1 is 2'
IF
(
t2.aValue2 = 2
)
SET #Description = #Description + ' t2.aValue2 is 2'
*/
END AS 'Description'
FROM [dbo].[Table1] t1
JOIN [dbo].[Table2] t2 ON t1.ID = t2.ID
So for example, if a row had a t1.aValue1 = 2 and t2.aValue1 = 2 then the output might look something like this.
ID | myType | myName | isEligible | Description
-----------------------------------------------
...
24 | Red | John | Not Eligible | t1.aValue1 is 2 t2.aValue1 is 2
25 | Blue | Eric | Eligible |
etc...
I am using SSMS 2008 R2.
How would I accomplish this?
You have the variable, but the expected results looks like you actually want it to the row? You can get it to the row just by using case, something like this:
END AS isEligible,
case when t1.aValue1 = 2 then 't1.aValue1 is 2 ' else '' end +
case when t1.aValue2 = 2 then 't1.aValue2 is 2 ' else '' end +
case when t2.aValue1 = 2 then 't2.aValue1 is 2 ' else '' end +
case when t2.aValue2 = 2 then 't2.aValue2 is 2 ' else '' end as Description

Need to arrange a record using while loop

While fetching details using while loop I am not able to get it as I want. What I want is to apply a loop and get details of each date. I am using SQL 2008.
Set #i = 1;
While (#NoOfDays >= #i)
Begin
SET #ManufactureQty = (Select isnull(SUM(Quantity),0) as Manufactured from IGN1 inner join OIGN on (OIGN.DocEntry = IGN1.DocEntry)
inner join OITM on (OITM.ItemCode = IGN1.ItemCode)
where Convert(Date,Cast(OIGN.DocDate as DATE)) = Convert(Date,DATEADD(d, #i, #date)) and OITM.ItmsGrpCod = #ItemGroup)
Select #i as D,OpeningBalance = case
when #i > 1 then ((isnull(SUM(OINM.InQty),0)-isnull(SUM(OINM.OutQty),0)) + ((isnull(SUM(OINM.InQty),0)-isnull(SUM(OINM.OutQty),0))))
when #i = 1 then (isnull(SUM(OINM.InQty),0)-isnull(SUM(OINM.OutQty),0))
end
,
isnull(#ManufactureQty,0) as Manufacture
From OITM
Inner Join OINM On (OINM.ItemCode = OITM.ItemCode and Convert(Date,Cast(OINM.DocDate as DATE)) = Convert(Date,DATEADD(d, #i, #date))) --and Convert(Date,Cast(OINM.DocDate as DATE)) > Convert(Date,'2014-05-01'))
Where OITM.ItmsGrpCod = #ItemGroup group by OINM.DocDate
SET #i = #i + 1
End
It Gives
D OpeningBalance Manufacture
1 123 23
D OpeningBalance Manufacture
2 143 773
D OpeningBalance Manufacture
3 126 27
.
But I need it like
D OpeningBalance Manufacture
1 123 23
2 143 773
3 126 27
.
Before loop:
create table #results (D int, OpeningBalance Int, Manufacture Int)
in loop
begin
insert into #results ...
select ...
end
--after
select * from #results

Rows to Columns in SQL Server 2000

I have this..
IDProspecto | IDObservacionCustomer | Observacion
---------------------------------------------------------
2204078 | 275214 | 03/9 Hable con Claudia me informa que Roberto ya se termino le deje..
2204078 | 294567 | 19/09 SOLICITAN LLAME MAÑANA A ALEJANDRO
2204078 | 295310 | 20/09 se envia mail a adrian
2204078 | 304102 | CIA SOLICITA NO INSTALE EQUIPO
And I want to have this...
idprospecto | observacion1 | observacion2 | observacion3 | observacion4 | observacionN
-----------------------------------------------------------------------------------------
2204078 | 03/09 Hable con clau... | 19/09 solicitan llame... | 20/09 se envia... | CIA solicita.. | ...
I read a lot about this but I found it hard to implement, since I never used cursor and pivot is not available in SQL Server 2000, I hope someone here can help me, thanks.
Since SQL Server 2000 does not have the PIVOT function, you should be able to use something similar to the following:
DECLARE #query AS NVARCHAR(4000)
DECLARE #rowCount as int
DECLARE #pivotCount as int
DECLARE #pivotRow as varchar(10)
set #rowCount = 1
set #pivotRow = ''
create table #colsPivot
(
id int IDENTITY(1,1),
name varchar(20),
CustId int
)
insert into #colsPivot
select 'Observacion', IDObservacionCustomer
from yourtable
set #pivotCount= (select COUNT(*) from #colsPivot)
-- reset rowcount
set #rowCount = 1
set #query = ''
---- create the CASE string
while #rowCount <= #pivotCount
begin
set #pivotRow = (select Top 1 CustId from #colsPivot)
set #query = #query + ', max(case when IDObservacionCustomer = ''' + #pivotRow + ''' then Observacion end) as ''Observacion_' + cast(#rowCount as varchar(10)) + ''''
delete from #colsPivot where CustId = #pivotRow
if #rowCount <= #pivotCount
begin
set #rowCount = #rowCount + 1
end
end
-- add the rest of the SQL Statement
set #query = 'SELECT IDProspecto ' + #query + ' from yourtable group by IDProspecto'
exec(#query)
See SQL Fiddle With Demo
You can try this example.
Prepare data:
create table tab1
(
IDProspecto int,
IDObservacionCustomer int,
Observacion varchar(130)
)
insert into tab1
values (2204078,275214 ,'03/9 Hable con Claudia me informa que Roberto ya se termino le deje..' )
insert into tab1
values (2204078,294567 ,'19/09 SOLICITAN LLAME MAÑANA A ALEJANDRO ' )
insert into tab1
values (2204078,295310 ,'20/09 se envia mail a adrian' )
insert into tab1
values (2204078,304102 ,'CIA SOLICITA NO INSTALE EQUIPO' )
We need identity field, so I create new table, and copy data from tab1.
create table tab2
(
id int identity,
IDProspecto int,
IDObservacionCustomer int,
Observacion varchar(130)
)
insert into tab2(IDProspecto,IDObservacionCustomer,Observacion)
select IDProspecto,IDObservacionCustomer,Observacion from tab1
Run query:
declare #max int, #inc int, #SqlSel varchar(2000),#SqlJoin varchar(2000), #Sql varchar(2000)
select #max = max(cnt) from (
select count(1) as cnt
from tab1
) T
select #inc = 1
select #SqlSel = 'select distinct t.IDProspecto '
select #SqlJoin = 'from tab2 t'
while #max>=#inc
begin
select #SqlSel= #SqlSel+', tab2'+convert(varchar,#inc)+'.Observacion as o'+convert(varchar,#inc)
select #SqlJoin = #SqlJoin+' left join tab2 as tab2'+convert(varchar,#inc)+' on t.IDProspecto = tab2'+convert(varchar,#inc)+'.IDProspecto and tab2'+convert(varchar,#inc)+'.id='+convert(varchar,#inc)
select #inc=#inc+1
end
select #SqlSel, #SqlJoin
exec( #SqlSel+' '+ #SqlJoin)

How to get rows having sum equal to given value

There is table contain
ID Qty
----------
1 2
2 4
3 1
4 5
Now if i had to choose rows where sum of Qty equals to 10,
How can i do this ?
like 2+4+1 = 7
but if i add 5 then 12
so ignore 2, then
4+1+5 = 10
How can i achieve this ?
Edit:
I want any possible combination which sums up to gives value.
suppose 7 then any rows which sums up to 7
like wise if 8 then any rows sums up to 8
want row/rows having combination equals to given value.
The problem you want to solve is called the subset sum problem. Unfortunately, it is NP-complete.
This means that, whether you use SQL or any other language to solve it, you will only be able to solve very small instances of the problem, i.e. ones with only a few entries in the table. Otherwise, the runtime will become excessive, since it grows exponentially with the number of rows in the table. The reason for this is that there is essentially no better way of finding the solution than to try all possible combinations.
If an approximate solution is acceptable, there is a polynomial time algorithm, which is described on the Wikipedia page.
If you want it to be exactly always three numbers that add to 10, then this
SELECT
*
FROM
MyTable t1
JOIN
MyTable t2 ON t1.ID <> t2.ID
JOIN
MyTable t3 ON t1.ID <> t3.ID AND t2.ID <> t3.ID
WHERE
t1.Qty + t2.Qty + t3.Qty = 10
If you want 2 or 4 or 5 numbers then you can't really do it in SQL
Edit:
Updated to ignore by ID not Qty
And again: If you want 2 or 4 or 5 numbers then you can't really do it in SQL
When you are dealing with such task in SQL you need to go to the cursors approach.
Cursors let you perform row by row operations and that's what you need, for example:
You want to make groups of where the summed quantity is 10
This are the tasks
select all the table into a temp table #TBL_ALL
loop row by row and when the rows sum up 10, delete from the temp table and insert into a final temp table #TBL_FINAL
do this until the #TBL_ALL sum cant be performed
An example:
Test table:
/****** Object: Table [dbo].[tblExample] Script Date: 06/09/2011 11:25:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblExample](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Qty] [int] NOT NULL,
CONSTRAINT [PK_tblExample] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Test Data:
INSERT INTO tblExample SELECT 2;
INSERT INTO tblExample SELECT 4;
INSERT INTO tblExample SELECT 1;
INSERT INTO tblExample SELECT 5;
INSERT INTO tblExample SELECT 5;
INSERT INTO tblExample SELECT 11;
INSERT INTO tblExample SELECT 1;
INSERT INTO tblExample SELECT 2;
INSERT INTO tblExample SELECT 3;
INSERT INTO tblExample SELECT 4;
INSERT INTO tblExample SELECT 7;
INSERT INTO tblExample SELECT 9;
INSERT INTO tblExample SELECT 1;
INSERT INTO tblExample SELECT 2;
Store procedure:
http://pastebin.com/EFeZcKXf
Results:
Grouped table:
ids qty group
12 9 1
7 1 1
11 7 2
9 3 2
4 5 3
5 5 3
2 4 4
10 4 4
14 2 4
Numbers not used:
id qty
1 2
8 2
3 1
13 1
6 11
Hope it helps
SP for those who cant access PasteBin
CREATE PROCEDURE getGroups
(
#groupByQty int, -- grouping number
#numberRuns int -- how many loops
-- usage: getGroups 10, 10
)
AS
SET NOCOUNT ON;
-- declare all variables
DECLARE #rowId int,
#rowQty int,
#rowTotal int,
#groupId int,
#totalRuns int,
#continue bit
-- set up our final temporary table
CREATE TABLE #TBL_COUNT
(
ids NVARCHAR(4000),
qty int,
[group] int
)
-- initializate variable
SET #groupId = 1;
SET #continue = 1;
SET #totalRuns = 0;
SELECT Id, Qty INTO #TBL_ALL FROM tblExample ORDER BY Qty DESC;
WHILE #totalRuns <= #numberRuns
BEGIN
-- declare the cursor
DECLARE Product CURSOR FOR SELECT Id, Qty FROM #TBL_ALL ORDER BY Qty DESC;
OPEN Product;
FETCH Product INTO #rowId, #rowQty;
PRINT ' ';
PRINT '### Run: ' + CAST(#totalRuns AS nvarchar(10)) + ' #################################################################';
PRINT 'Grouping Table by ' + CAST(#groupByQty AS nvarchar(10)) + ' | group id = ' + CAST(#groupId AS nvarchar(10));
-- Retrieve and process the first row
SELECT Top 1 #rowId = Id, #rowQty = Qty FROM #TBL_ALL ORDER BY Qty DESC;
PRINT 'First Row: id = ' + CAST(#rowId AS nvarchar(10)) + ' | qty = ' + CAST(#rowQty AS nvarchar(10));
-- sum it up and see if we have #groupByQty
SELECT #rowTotal = ISNULL(SUM(qty),0) FROM #TBL_COUNT WHERE [group] = #groupId;
PRINT 'Current sum in #TBL_COUNT: #groupId = '+ CAST(#groupId AS nvarchar(10)) +' | #rowTotal = ' + CAST(#rowTotal AS nvarchar(10)) + ' | (#rowTotal + #rowQty) = ' + CAST((#rowTotal + #rowQty) AS nvarchar(10));
IF #rowQty > #groupByQty
BEGIN
PRINT ' x First row has an unused number';
END
ELSE
BEGIN
-- handle result
IF (#rowTotal + #rowQty) = #groupByQty
BEGIN
PRINT '+++ Current sum is ' + CAST(#groupByQty AS nvarchar(10)) + ' +++';
-- save number
INSERT INTO #TBL_COUNT SELECT #rowId, #rowQty, #groupId;
PRINT '### Inserted final # into #TBL_COUNT : id = ' + CAST(#rowId AS nvarchar(10)) + ' | qty = ' + CAST(#rowQty AS nvarchar(10)) + ' | group = ' + CAST(#groupId AS nvarchar(10));
-- remove from table as we use it already
DELETE FROM #TBL_ALL WHERE Id = #rowId;
-- we got 10, let's change our Groupping
SET #groupId = (#groupId + 1);
PRINT 'New group id: ' + CAST(#groupId AS nvarchar(10));
END
ELSE
BEGIN
IF (#rowTotal + #rowQty) < #groupByQty
BEGIN
PRINT '### Inserted into #TBL_COUNT : id = ' + CAST(#rowId AS nvarchar(10)) + ' | qty = ' + CAST(#rowQty AS nvarchar(10)) + ' | group = ' + CAST(#groupId AS nvarchar(10));
-- save number
INSERT INTO #TBL_COUNT SELECT #rowId, #rowQty, #groupId;
-- remove from table as we use it already
DELETE FROM #TBL_ALL WHERE Id = #rowId;
END
ELSE
BEGIN
PRINT ' x Unmatch number, will handle this latter';
END
END
END
-- start the main processing loop
WHILE ##Fetch_Status = 0
BEGIN
FETCH Product INTO #rowId, #rowQty;
PRINT '##Fetch_Status = ' + CAST(##Fetch_Status AS nvarchar(100));
IF ##Fetch_Status < 0
BEGIN
BREAK
END
-- we have the values of our row, let's use them
PRINT 'Fetched Row: id = ' + CAST(#rowId AS nvarchar(10)) + ' | qty = ' + CAST(#rowQty AS nvarchar(10));
-- sum it up and see if we have #groupByQty
SELECT #rowTotal = ISNULL(SUM(qty),0) FROM #TBL_COUNT WHERE [group] = #groupId;
PRINT 'Current sum in #TBL_COUNT: #groupId = '+ CAST(#groupId AS nvarchar(10)) +' | #rowTotal = ' + CAST(#rowTotal AS nvarchar(10)) + ' | (#rowTotal + #rowQty) = ' + CAST((#rowTotal + #rowQty) AS nvarchar(10));
-- handle result
IF (#rowTotal + #rowQty) = #groupByQty
BEGIN
PRINT '+++ Current sum is ' + CAST(#groupByQty AS nvarchar(10)) + ' +++';
-- save number
INSERT INTO #TBL_COUNT SELECT #rowId, #rowQty, #groupId;
PRINT '### Inserted final # into #TBL_COUNT : id = ' + CAST(#rowId AS nvarchar(10)) + ' | qty = ' + CAST(#rowQty AS nvarchar(10)) + ' | group = ' + CAST(#groupId AS nvarchar(10));
-- remove from table as we use it already
DELETE FROM #TBL_ALL WHERE Id = #rowId;
-- we got 10, let's change our Groupping
SET #groupId = (#groupId + 1);
PRINT 'New group id: ' + CAST(#groupId AS nvarchar(10));
-- start again
BREAK;
END
ELSE
BEGIN
IF (#rowTotal + #rowQty) < #groupByQty
BEGIN
PRINT '### Inserted into #TBL_COUNT : id = ' + CAST(#rowId AS nvarchar(10)) + ' | qty = ' + CAST(#rowQty AS nvarchar(10)) + ' | group = ' + CAST(#groupId AS nvarchar(10));
-- save number
INSERT INTO #TBL_COUNT SELECT #rowId, #rowQty, #groupId;
-- remove from table as we use it already
DELETE FROM #TBL_ALL WHERE Id = #rowId;
END
ELSE
BEGIN
PRINT ' x Unmatch number, will handle this latter';
END
END
END -- END WHILE ##Fetch_Status = 0
SET #totalRuns = #totalRuns + 1;
-- Close and dealocate
CLOSE Product;
DEALLOCATE Product;
END -- END WHILE totalRuns <= #numberRuns
-- let's sum our last group and remove it if it's not #groupByQty
SELECT #rowTotal = ISNULL(SUM(qty),0) FROM #TBL_COUNT WHERE [group] = #groupId;
IF #rowTotal <> #groupByQty
BEGIN
SET IDENTITY_INSERT #TBL_ALL ON
INSERT INTO #TBL_ALL (Id, Qty) SELECT Ids, Qty FROM #TBL_COUNT WHERE [group] = #groupId;
DELETE FROM #TBL_COUNT WHERE [group] = #groupId;
END
SET NOCOUNT OFF;
-- Show and Delete temp tables
SELECT * FROM #TBL_COUNT;
SELECT * FROM #TBL_ALL;
DROP TABLE #TBL_COUNT;
DROP TABLE #TBL_ALL;
P.S. I'm not a SQL Professional, so bear with me if I did something weird, and keep in mind that this is a performance waste, maybe someone can use the the Loop without Cursors, more in this page
If u add always 3 numbers its like gbn said, if not then u have to check every combination of ur rows which gives u 2 to the number_of_rows power cobinations and i dont see how can it be done on sql in one query. If u use loop in sql sure its possible but u should find some good algorithm to finish this task.