Selecting Rows With Sums Equal To A Given Number
Nov 2, 2003
You are given say a pricelist of books. And you have to find out
all possible sets of books, each of them having total sum of book
prices equal to a given number.
set nocount on
if object_id('tempdb..#t')>0 drop table #t
if object_id('tempdb..#tt')>0 drop table #tt
create table #t (n int, price int)
insert into #t -- note asc order of book prices
select 1, 1 union all
select 2, 3 union all
select 3, 4 union all
select 4, 5 union all
select 5, 7 union all
select 6, 7 union all
select 7, 11 union all
select 8, 15 union all
select 9, 20 union all
select 10, 20 union all
select 11, 22 union all
select 12, 28 union all
select 13, 33 union all
select 14, 40 union all
select 15, 43 union all
select 16, 47 union all
select 17, 50 union all
select 18, 55 union all
select 19, 56 union all
select 20, 63
go
create table #tt (n int, price int)
go
declare @rows int, @p int, @sum int set @sum=16
delete from #t where price>@sum
set @p=(select sum(price) from #t)
if @p>=@sum
begin
set @rows=(select max(n) from #t)
declare @n int, @s int
set @n=@rows+1 set @s=0
while 0=0
begin
while @n>1
begin
set @n=@n-1
if @s+(select price from #t where n=@n)<=@sum
and @s+(select sum(price) from #t where n<=@n)>=@sum
begin
set @s=@s+(select price from #t where n=@n)
insert into #tt select n, price from #t where n=@n
if @s=@sum select * from #tt --- outputting
end
end
set @n=(select min(n) from #tt)
set @s=@s-(select price from #tt where n=@n)
delete from #tt where n=@n
if @s=0 and (select sum(price) from #t where n<@n)<@sum break
end
end
drop table #tt
drop table #t
Result for @sum=16 (for e.g. @sum=76 number of different sets = 196):
n price
----------- -----------
8 15
1 1
n price
----------- -----------
7 11
4 5
n price
----------- -----------
7 11
3 4
1 1
n price
----------- -----------
6 7
4 5
3 4
n price
----------- -----------
6 7
4 5
2 3
1 1
n price
----------- -----------
5 7
4 5
3 4
n price
----------- -----------
5 7
4 5
2 3
1 1
EDIT: added one more condition (in blue) into an IF statement.
Now it works incredibly fast.
View 4 Replies
ADVERTISEMENT
Jun 24, 2008
Hello all.
Im trying to write a stored procedure which i can stipulate the top number of rows it returns. I know i use the following syntax:
SELECT TOP 5
And i know i need to pass the number of rows i want as a variable to the stored proceudre like:
@Top as Integer
But when i try and do the following. SQL Server complains about the syntax:
SELECT TOP @Top
Can anyone advise me how i should be doing this?
View 3 Replies
View Related
Jul 30, 2007
I know I can use "First" to specify a number of rows to return from a query but is it possible for the number of rows returned to be based on a parameter, something like this:
SELECT FIRST @someNumber name, age
FROM friends
WHERE age > @ageInput
View 3 Replies
View Related
Jun 23, 2015
Got this query and I need the following result;
declare @NumberToCompareTo int
set @NumberToCompareTo = 8
declare @table table
(
number int
)
insert into @table
select 4
[Code] ....
The query selects 4 and 5 of course. Now what I'm looking for is to retrieve the number less or equal to @NumberToCompareTo, I mean the most immediate less number than the parameter. So in this case 5
View 4 Replies
View Related
Feb 20, 2008
Hi,
When expoting data from excel to sql server table, using SSIS package, after exporting is done, how would i check source rows are equal to destination rows. If not to throw an error message.
How can we handle transactions in SSIS
1. when some error/something happens during export and the # of rows are not exported fully to destination, how to rollback the transaction in SSIS.
Any sort of help would be highly appreciated.
Thanks,
View 2 Replies
View Related
Feb 20, 2008
Hi,
When expoting data from excel to sql server table, using SSIS package, after exporting is done, how would i check source rows are equal to destination rows. If not to throw an error message.
Any sort of help would be highly appreciated.
Thanks,
View 1 Replies
View Related
Apr 12, 2007
Hello All
I am trying to figure out if what i am attempting to do is possible and whether or not my approach is wrong to begin with.
I am trying to build a custom report for our accounting system which is Traverse from Open systems. This is what i have done in the stored procedure thus far
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
ALTER PROCEDURE rptArFLSalesByCustItemized_sp
@custId pCustID,
@dateFrom datetime,
@dateThru datetime,
@itemIdFrom pItemId,
@itemIdThru pItemId
as
set nocount on
-- define some variables for previous year
declare @LYqty int, @LyAmt money, @LYfrom datetime, @LYthru datetime
-- set defaults
SET @itemIdFrom=ISNULL(@itemIdFrom,(SELECT MIN(itemId) FROM tblInItem))
SET @itemIdThru=ISNULL(@itemIdThru,(SELECT MAX(itemId) FROM tblInItem))
SET @LYfrom=DATEADD(YEAR,-1,@dateFrom)
SET @LYthru=DATEADD(YEAR, -1, @dateThru)
-- create small temp table to hold customer info
Create Table #tmpArCustInfo
(
custId pCustID,
custName VARCHAR (30),
)
-- populate customer temp table with info
Insert into #tmpArCustInfo
select custId, custName
from tblArCust
WHERE custId = @custId
-- create a temp table to hold the Data for each Item
Create Table #tmpArSalesItemized
(
itemId pItemId,
productLine VARCHAR (12),
pLineDesc VARCHAR (35),
descr VARCHAR (35),
LYQtySold int,
LYTDQtySold int,
QtySold int,
LYTDsales money,
totalSales money,
LastInvDate datetime,
)
-- populate the temp table with all of the inventory items
insert into #tmpArSalesItemized
select ii.itemId, ii.productLine, ip.Descr, ii.Descr, 0,0,0,0,0, NULL
from tblInItem ii, tblInProductLine ip
where ip.productLine = ii.productLine
AND ii.itemId BETWEEN @itemIdFrom AND @itemIdThru
-- update table with this years quantities
update #tmpArSalesItemized
SET QtySold = (select SUM(QtyOrdSell) from tblArHistDetail hd
where TransId IN (select TransId from tblArHistHeader where custId = @custId)
AND orderDate IN (select OrderDate from tblArHistHeader where OrderDate BETWEEN @dateFrom AND @dateThru)
AND hd.partId BETWEEN @itemIdFrom AND @itemIdThru
GROUP BY hd.partId
)
-- Return the temp tables results
select * from #tmpArSalesItemized, #tmpArCustInfo
drop table #tmpArSalesItemized, #tmpArCustInfo
return
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
My problems begin where i want to start updating all of the Qty's of the QtySold field. I have managed to get it to write the same sum in every field but i cannot figure out how to update each row based on the sum of the qty found for that item in the tblArHistDetails table, trouble is too that there is no reference to the custId in that table either. The custId resides in tblArHistHeader and is linked to the details table via the TransId column. So really i need to update many rows based on criteria from 2 other tables.
Can anyone please help? I dont have a clue how to make this work, and most of what i have learned about sql thus far has been from opening other stored procs etc in the accounting system and just reading to see how the developers have done things.
Thanks
Jamie
View 1 Replies
View Related
May 25, 2015
How to find the equal and opposite rows in a table.
E.g.:
book position
A 500
B -500
C -500
The output should return the rows having equal and opposite positions.
O/P:
A 500
B -500
I have tried self join on a table but in vain.Do we need to cursors for these row level handling?
View 6 Replies
View Related
Jun 14, 2006
Dear Friends,
In my report, I am having Listbox for users to choose Country, City & Company.
The user can choose Country. Based on the country selection, cities will be listed out.
Based on the city selection, Companies will be listed out.
They can choose companies.
Now, I have to show two set of results.
A. List of Companies as per selection ( dataset with equal to selection )
B. List of Companies which are not selected ( ie dataset with not equal to selection )
I have created a dataset with all companies and filter it by selection. When I tried with the filter option in the Dataset, I am able to check for only one value and not for multiple value. If the selection is one company, then I can filter it. But if they choose 5 companies, I am not not able to filter it. Is there any other option I can try out.
Please advice. Thanks.
warm regards
Rakin
Singapore.
View 6 Replies
View Related
Mar 25, 2002
I'm stuck. I have a table that I want to pull some info from that I don''t know how to.
There are two colomuns, one is the call_id column which is not unique and the other is the call_status column which again is not unique. The call_status column can have several values, they are ('1 NEW','3 3RD RESPONDED','7 3RD RESOLVED','6 PENDING','3 SEC RESPONDED','7 SEC RESOLVED').
i.e example, this is the existing data.
Call_id Call_Status
555555 3 3RD RESPONDED
235252 7 SEC RESOLVED
555555 7 3RD RESOLVED
325252 6 PENDING
555555 6 PENDING
325235 3 SEC RESPONDED
555555 1 NEW
This is the data I want...
Call_id Call_Status
555555 3 3RD RESPONDED
555555 6 PENDING
555555 7 3RD RESOLVED
The call_id could be any number, I only want the 6 PENDING rows where there are other rows for that call_id which have either 3 3RD RESPONDED or 7 3RD RESOLVED. If someone knows how it would be a great help.
Cheers,
Chris
View 1 Replies
View Related
Sep 24, 2007
Hi
I want to enter rows into a table having more number of columns
For example : I have one employee table having columns (name ,address,salary etc )
then, how can i enter 100 employees data at a time ?
Suppose i am having my data in .txt file (or ) in .xls
( SQL Server 2005)
View 1 Replies
View Related
Apr 16, 2008
Hi,
Here is a basic example of the issue I am having:
Table 1 columns - name, address, zipcode, favorite food
For table 2 I want to find how many zipcodes exists and also take 20% of the count
Table 2 columns - based off Table 1 contains zipcode, count(zipcode) as ct, count(zipcode) * .20 as perc_ct
For example:
zipcode ct perc_ct
83746 10 2
93847 20 4
I want to run a query that will pull any 2 records for 83746 and any 4 records for 93847 from Table 1.
Is this possible?
View 1 Replies
View Related
Jul 20, 2005
I have table1 and table2.In table1 I have a column of numbers, numbers1.In table2 I have a column of numbers, numbers2.I'd like to select the highest number represented in either column.Example:table1:column1--------------345565643656555676table2:column2--------------3456564556456456456456The number I would want would be 56456 since it's the largest numberout of all combined.How can I get that number with one select statement?--[ Sugapablo ][ http://www.sugapablo.com <--music ][ http://www.sugapablo.net <--personal ][ Join Bytes! <--jabber IM ]
View 1 Replies
View Related
Nov 27, 2007
selecting number of products that comes under a parent categorysqlserver2005CREATE TABLE [ProductCategoryAssociation]([CategoryID] [bigint] , --this is primary key of table Category[ProductID] [bigint] ,--this is primary key of table product) the above table binds a product to its category CEATE TABLE [Category]([CategoryID] [bigint] IDENTITY(1,1) -- this is primary key of table category[Name] [nvarchar](255)[ParentCategory] [bigint] NULL,) I have a Category"A" as a supper parentcategoryI have 1product in Category"A"Category"A" have 2 child category A11,A12. A11,A12 both have 2 products in the category (totally 4)Now I can get the count of all product belong Category"A" (ie is 5= 1+2*2) fivelet 1 be the id of category "A" Now the following querry give me the expected resultselect count(ProductId) from ProductCategoryAssociation where categoryid=1 or categoryid in (select categoryid from Category where Parentcategory=1) BUT if i have child for A11 named A111 and if there is ONE product belong to A111 this querry wont take that in to cosiderationso the following querry will do itselect count(ProductId) from ProductCategoryAssociation where categoryid=1 or categoryid in (select categoryid from Category where Parentcategory=1 or Parentcategory in (select categoryid from Category where Parentcategory=1))ie i nested one more selectbuthis has limitationsSo kindly give me a general solution to check up to the las level of category
View 8 Replies
View Related
Jan 7, 2002
how can I select 10 random rows from a table?
Please help
View 2 Replies
View Related
Sep 12, 2001
Hello,
Does anyone know how to select rows by their position in a table. I need to be able to e.g return the 2,000th - 2,200th rows as a set. I will have many concurrent clients connecting to this table so I do not want to use cursors. The table is 800,000 in length.
Any ideas people?
Thanks,
Alan
View 2 Replies
View Related
Nov 28, 2007
Hi,
I've a table the following table:
ActDate datetime
CustomerID int
data on the table:
6/27/2007 10:23:22 AM
113
6/27/2007 10:25:20 AM
113
6/27/2007 11:38:34 AM
76
6/27/2007 5:23:22 PM
212
6/28/2007 11:58:58 AM
110
6/28/2007 12:24:17 PM
110
6/28/2007 12:27:15 PM
110
7/3/2007 5:16:44 PM
63
7/3/2007 5:16:56 PM
63
7/12/2007 3:35:50 PM
98
7/13/2007 3:30:05 PM
110
7/13/2007 3:32:49 PM
110
7/13/2007 3:38:01 PM
110
7/13/2007 3:46:00 PM
110
7/14/2007 10:25:55 AM
82
7/15/2007 9:19:11 AM
18
7/21/2007 3:53:16 PM
34
7/23/2007 11:53:43 AM
84
7/23/2007 11:55:24 AM
84
7/23/2007 11:55:48 AM
84
7/24/2007 7:41:31 PM
116
7/27/2007 9:39:52 AM
110
7/27/2007 12:41:49 PM
18
7/28/2007 11:00:55 AM
113
7/31/2007 10:11:31 AM
82
8/1/2007 5:56:23 PM
98
8/2/2007 7:22:16 PM
77
8/2/2007 8:28:11 PM
77
I need to filter the table in order to have only a record by CustomerID with the higher date.
Thanks in Advance
JP
View 3 Replies
View Related
Jun 11, 2008
Hi,
I want to select the 8 most saled products from large orders table... the problem is that when i use the "distinct" sentence (something like this- "SELECT TOP 8 distinct id, products, productid FROM tbl_orders ORDER BY id") I get back the distinct of any columns.... (and any ID is distinct, of course), but if i don't include the id's in the distinct sentence, i can't order by id's.
can i get the last orders, only by distinct product, and not by distinct id, and order them by the id's?
View 17 Replies
View Related
Jan 7, 2004
I have a temporary table that contain 1000 rows. I want to insert records from 900 to 1000 into another temporary table. Is ther any query that will do this in SQL server. With cursors I can do that but I need one shot query. Please give me some suggestions.
I using this query but it is not returning any rows.
select * into #t2 from #t1 t1 where not exists( select top 900 * from #t1 t2)
View 6 Replies
View Related
Oct 31, 2013
I have two tables a stock table and a price table and I want to select the correct price for the Stock Date.
Problem is sometimes there is a promotion date in the price table between the live dates so the rows double up. Below is my sql but I get over 17,000 rows when it should be about 16,964.
I will post up the table and data.
SELECT a.[Company]
,a.[ProductID]
,a.[ColourSize]
,a.[StockDate]
,a.[Quantity]
,b.[Ticket Price]
FROM[Stock_Ledger] a
LEFT OUTER JOIN [Product_Prices] b
ON a.[Company] = b.[Company]
AND a.[ProductID] = b.[ProductID]
AND a.[ColourSize] = b.[ColourSize]
AND a.[StockDate] BETWEEN b.[StartDate] AND b.[EndDate]
ORDER BY a.[StockDate],a.[ProductID],a.[ColourSize]
View 7 Replies
View Related
Jun 5, 2006
Mike writes "Hi,
I am a beginner with TSQL and I hope this is not a silly question :-)
Lets say I have a table with 2 columns, 1 a primary key identity field with increment 1 and the other a char.
EG:
ID ANIMAL
---------
1 CAT
2 DOG
3 PIG
4 RAT
5 PIG
6 DOG
7 DOG
.
.
And so on with many entries
How do I return a selection of rows that have the contents of the ANIMAL field matching 1 or more times
EG:
From above table I want to return rows 2,6 & 7 and 3 & 5 ONLY and not 1(CAT) and 4(RAT) because they only occur once.
In my real life situation I have unknown numeric data in field 2 but the principal is the same.
How do I do this?
Thanks in Advance
Mike"
View 2 Replies
View Related
Sep 25, 2006
I have a table stock, on the table I have company_name, stock_value, sector.
Now I want to get top five rows from this table depending on the five highest value of stock_value and for each sector. The query has to run on both oracle DB and Microsoft SQL Server with top priority MSSQL.
I will appreciate if you help me on this
jideofor
View 2 Replies
View Related
Jul 23, 2005
Hi experts,I have been trying to limit the table rows in the following situation,any suggestions will be appreciated.we have table called tempTb has columns id, c_id, c_name, rating, datecolumns.id is an identity column.date is a datetime column, the rest are varchar datatype.Here is the table structure with sample data,idc_idc_nameratingdate1aoamer onli11/1/20022aoamer onli13/1/20023aoamer onli16/1/20024aoamer onli39/1/20025aoamer onli312/1/20026aoamer onli33/1/20037aoamer onli36/1/20038aoamer onli39/1/20039aoamer onli212/1/200310aoamer onli16/1/200411aoamer onli112/1/200412xyxabs yasd11/1/200213xyxabs yasd23/1/200214xyxabs yasd26/1/200215xyxabs yasd29/1/200216xyxabs yasd112/1/200217xyxabs yasd13/1/200318xyxabs yasd36/1/200319xyxabs yasd39/1/200320xyxabs yasd212/1/200321xyxabs yasd16/1/200422xyxabs yasd112/1/2004[color=blue]>From this table I need to select the rows with rating changes only,[/color]i.e if two or three consecutive rows have same rating only the firstrow should be selected.the selection should look like...idc_idc_nameratingdate1aoamer onli11/1/20024aoamer onli39/1/20029aoamer onli212/1/200310aoamer onli16/1/200412xyxabs yasd11/1/200213xyxabs yasd23/1/200216xyxabs yasd112/1/200218xyxabs yasd36/1/200320xyxabs yasd212/1/200321xyxabs yasd16/1/2004I was trying to do this by self-joining the table like....select t1.* from tempTb t1, tempTb t2where t1.id!=t2.id,t1.c_id=t2.c_id,t1.c_name=t2.c_name,t1.rating!=t2.rating.But this is generating cartesian products,I have tried some other combinations after where clause with date colmnwtc,but none seems to give the required result.so if anybody can guide me in the right direction I would appreciateit.Thanks alot,Remote
View 4 Replies
View Related
Jul 23, 2005
Hello All,I have this table:CREATE TABLE [dbo].[tbl_TESTING] ([ROW_ID] [int] IDENTITY (1, 1) NOT NULL ,[FNAME] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[LASTNAME] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[MOVEDINYR] [int] NULL ,[MOVEDOUTYR] [int] NULL) ON [PRIMARY]GOwith these records:INSERT INTO tbl_TESTINGVALUES('JAMES', 'TAYLOR', '1995', '2000')INSERT INTO tbl_TESTINGVALUES('JAMES', 'TAYLOR', '1994', '2005')What I would like to do is be able to select FIRSTNAME, LASTNAME,MIN(MOVEDINYR), MAX(MOVEDOUTYR) for JAMES TAYLOR e.g.FIRSTNAME=JAMESLASTNAME=TAYLORMOVEDINYR=1994MOVEDOUTYR=2005Some sql syntax help appreciated,thanks in advance!
View 2 Replies
View Related
Apr 20, 2006
hi!I have two tables with same structure. I need to run a select query thatwill return only the rowsfrom one table that are not in the other.In MySQL it would beselect * from table1 MINUS select * from table2.but in MsSql I can not find the apropriate way to do this.Any Help?Zvonko
View 3 Replies
View Related
Jan 23, 2008
Is it posible on a query ordered by employee name, for exemple, that MSSQL gives me a position of which employee is contained on the recordset?
that's my query (simplified)
SELECT name, payment, category FROM employee_payments ORDER BY name
John, 1000, sallary
Peter, 1500, sallary
Peter, 500, other
Zeus, 1000, sallary
I want to add another field giving me the position of the employee on the recordset:
John, 1000, sallary, 1
Peter, 1500, sallary, 2
Peter, 500, other, 2
Zeus, 1000, sallary, 3
Is it posible?
View 5 Replies
View Related
Jun 25, 2015
I have questions and answers from one table, I need to select questions as column names and answers column values as the results for the questions column.
View 28 Replies
View Related
Mar 20, 2008
I got the following query:SELECT TOP (8) ext.extID, ext.Quote, ext.sourceTitle, ext.extRating, gf_game.gameID, gf_game.catID, gf_game.URL, gf_game.TitleFROM gf_game_ext AS ext INNER JOIN gf_game ON gf_game.gameID = ext.gameIDWHERE (ext.Approved = 1)ORDER BY ext.extID DESC which is e.g. producing this output: 6000 -some text- Title 90 1960 2 tom-cl tom cl5999 -some text- title 90 1960 2 tom-clcl asdf5998 -some text- title 90 1959 2 tom-cl-cl asdfWhat I'd like to do now is to filter out the duplicate GameIDs (= 1960) so that just one unique row with the gameid 1960 is remaining. If I put in a SELECT DINSTINCT TOP(8) it just counts for the table ext, but I need it to count for gf_game.gameID - is that possible?Thanks a lot!
View 9 Replies
View Related
Jul 3, 2000
Hi all -
is there a way to process a file x records at a time?
We have a table that I need to append to an existing table. The date columns are currently in char but must be converted to datetime for the existing table. The problem is I have bad data. There are 3 million rows where the date field isn't valid for SQL's datetime format. Since this is the data I have, I have to work with it. I would like for SQL to just insert a null if it comes upon a bad date. Currently when it encounters a field that isn't valid, it stops the process with an error.
I have tried to go around it below, but there is still something "hanging" I would like to be able just to insert one million rows at a time and if it errors, then I can look at the next million, find the error, fix it and continue on.
Any suggestions? Or if you have a better idea all together I would love to see it.
SQL Server 7.0, SP2
,CASE
when
(substring(check_date,1,4) not between '1997' and '2000' or
substring(check_date,5,2) not between '01' and '12' or
substring(check_date,7,2) not between '01' and '31') THEN null
ELSE cast(check_date as datetime)
END AS check_date
Thanks,
Michelle
View 1 Replies
View Related
Jan 25, 2001
Hy!
I'm trying to write a query which returns only some rows in my table...
For example :
I want all the rows included between 30 and 50 from table XYZ
(30 and 50 are not keys but really the numbers of records)
Is there someone out there who has a hint for me???
Thank you for your help and sorry for my english!
RadiFluide
View 1 Replies
View Related
Dec 15, 1999
I need to select the last 6 rows from a table... I was doing it like this:
select * from table where id > (select max(id)-6 as id from table)
But if one of the records is deleted it will only show 5.... Is there any easy way to make it show the bottom 6 records?
much thanks sql gods...
View 2 Replies
View Related
Aug 20, 2013
I have to select rows based on if the transaction date = todays date.The column is defined as numeric 8 with 0 decimal.how to code for todays date with such a column?
View 8 Replies
View Related