Sum Up An Unknown Number Of Records

Mar 19, 2007

With this algorithm you can sum up an unkown number of records, so that an aggregation matches a fixed value.
If there is not an exakt match available, the algorithm returns the nearest possible value!-- Initialize the search parameter
DECLARE@WantedValue INT

SET@WantedValue = 349

-- Stage the source data
DECLARE@Data TABLE
(
RecID INT IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
MaxItems INT,
CurrentItems INT DEFAULT 0,
FaceValue INT,
BestUnder INT DEFAULT 0,
BestOver INT DEFAULT 1
)

-- Aggregate the source data
INSERT@Data
(
MaxItems,
FaceValue
)
SELECTCOUNT(*),
Qty
FROM(
SELECT 899 AS Qty UNION ALL
SELECT 100 UNION ALL
SELECT 95 UNION ALL
SELECT 50 UNION ALL
SELECT 55 UNION ALL
SELECT 40 UNION ALL
SELECT 5 UNION ALL
SELECT 100 UNION ALL
SELECT 100 UNION ALL
SELECT 100 UNION ALL
SELECT 100 UNION ALL
SELECT 100 UNION ALL
SELECT 50 UNION ALL
SELECT 250 UNION ALL
SELECT 100 UNION ALL
SELECT 100 UNION ALL
SELECT 100 UNION ALL
SELECT 100 UNION ALL
SELECT 100 UNION ALL
SELECT 100 UNION ALL
SELECT 100 UNION ALL
SELECT 100 UNION ALL
SELECT 100 UNION ALL
SELECT 90 UNION ALL
SELECT 100 UNION ALL
SELECT 100 UNION ALL
SELECT 100 UNION ALL
SELECT 100 UNION ALL
SELECT 100 UNION ALL
SELECT 100 UNION ALL
SELECT 50 UNION ALL
SELECT 350 UNION ALL
SELECT 450 UNION ALL
SELECT 450 UNION ALL
SELECT 100 UNION ALL
SELECT 100 UNION ALL
SELECT 50 UNION ALL
SELECT 50 UNION ALL
SELECT 50 UNION ALL
SELECT 1 UNION ALL
SELECT 10 UNION ALL
SELECT 1
) AS d
GROUP BYQty
ORDER BYQty DESC

-- Declare some control variables
DECLARE@CurrentSum INT,
@BestUnder INT,
@BestOver INT,
@RecID INT

-- If productsum is less than or equal to the wanted sum, select all items!
IF (SELECT SUM(MaxItems * FaceValue) FROM @Data) <= @WantedValue
BEGIN
SELECTMaxItems AS Items,
FaceValue
FROM@Data

RETURN
END

-- Delete all unworkable FaceValues
DELETE
FROM@Data
WHEREFaceValue > (SELECT MIN(FaceValue) FROM @Data WHERE FaceValue >= @WantedValue)

-- Update MaxItems to a proper value
UPDATE@Data
SETMaxItems =CASE
WHEN 1 + (@WantedValue - 1) / FaceValue < MaxItems THEN 1 + (@WantedValue - 1) / FaceValue
ELSE MaxItems
END

-- Update BestOver to a proper value
UPDATE@Data
SETBestOver = MaxItems

-- Initialize the control mechanism
SELECT@RecID = MIN(RecID),
@BestUnder = 0,
@BestOver = SUM(BestOver * FaceValue)
FROM@Data

-- Do the loop!
WHILE @RecID IS NOT NULL
BEGIN
-- Reset all "bits" not incremented
UPDATE@Data
SETCurrentItems = 0
WHERERecID < @RecID

-- Increment the current "bit"
UPDATE@Data
SETCurrentItems = CurrentItems + 1
WHERERecID = @RecID

-- Get the current sum
SELECT@CurrentSum = SUM(CurrentItems * FaceValue)
FROM@Data
WHERECurrentItems > 0

-- Stop here if the current sum is equal to the sum we want
IF @CurrentSum = @WantedValue
BREAK
ELSE
-- Update the current BestUnder if previous BestUnder is less
IF @CurrentSum > @BestUnder AND @CurrentSum < @WantedValue
BEGIN
UPDATE@Data
SETBestUnder = CurrentItems

SET@BestUnder = @CurrentSum
END
ELSE
-- Update the current BestOver if previous BestOver is more
IF @CurrentSum > @WantedValue AND @CurrentSum < @BestOver
BEGIN
UPDATE@Data
SETBestOver = CurrentItems

SET@BestOver = @CurrentSum
END

-- Find the next proper "bit" to increment
SELECT@RecID = MIN(RecID)
FROM@Data
WHERECurrentItems < MaxItems
END

-- Now we have to investigate which type of sum to return
IF @RecID IS NULL
IF @WantedValue - @BestUnder < @BestOver - @WantedValue
-- If BestUnder is closer to the sum we want, choose that
SELECTBestUnder AS Items,
FaceValue
FROM@Data
WHEREBestUnder > 0
ELSE
-- If BestOver is closer to the sum we want, choose that
SELECTBestOver AS Items,
FaceValue
FROM@Data
WHEREBestOver > 0
ELSE
-- We have an exact match
SELECTCurrentItems AS Items,
FaceValue
FROM@Data
WHERECurrentItems > 0With references to
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=73540
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=73610
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=78015
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=79505


Peter Larsson
Helsingborg, Sweden

View 3 Replies


ADVERTISEMENT

Unknown Number Of Values

Mar 19, 2008

I'm on SQL Server 2005 SP2.

I have the old age question of how to process a string parameter that is passed to a Stored Procedure that has an unknown number values. The example below has 5 values but it could be anywhere between 1 and 20.

I basically need to extract each value to Insert these values into the appropriate tables.

In the SQL 2000 days I use to do this with some T-SQL code that determines where the comma is and then I get the value and so on.....

I have read somewherethat this can be achieved using the XML Data Type.

Can someone show me that or atleast get me started on how to achiev this?

DECLARE @Range VARCHAR(200)


SET @Range = '10, 4, 8, 6, 22'

View 5 Replies View Related

FnParseString And Unknown Number Of Columns

Mar 20, 2007

Keshka writes "I'm using function fnParseString form http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=76033 in some of my sp.

it's very helpfull, but my question is if there is a way to split variable into columns if I don't know how many columns I'll have? It could be 1 or 2 or 3 and etc.


Thanks"

View 3 Replies View Related

Package For Unknown Number Of Sources

Nov 21, 2007



Hi,

I need to write a SSIS package. The source are in a Windows folder where there are a variable number of text files. These text files may vary in number everyday, How can i write a package for variable number of sources.

Please respond.

Thanks,
Swapna

View 1 Replies View Related

How To Present An Unknown Number Of Columns And Their Names

Aug 14, 2001

I've got a database with an unknown number of columns. Hence, the column names are also unknown. What's the easiest SQL to present the values in each column and the column headings?

View 1 Replies View Related

Transact SQL :: Convert Unknown Number Of Questions From Rows Into Columns

Jun 17, 2015

Using the following tables and data---

CREATE TABLE tblRiskReviewHistory(RiskReviewID int, RiskReviewHistoryID int, Name nvarchar(20), Description nvarchar(50), Date date)
INSERT tblRiskReviewHistory(RiskReviewID, RiskReviewHistoryID, Name, Description, Date)
VALUES(1,1,'Customer A','Profile Assessment','01/01/2015'),
(1,2,'Customer B','Profile Assessment','02/20/2015')

[Code] ...

And currently outputs;

Name Description Date Question Answer
Customer A Profile Assessment 01/01/2015

How complex is the structure?

Customer A
Profile Assessment
01/01/2015
The total value of assets?
Less than GBP 1 million

Customer A
Profile Assessment
01/01/2015
The volume of transactions undertaken?
Low (-1 pmth)

[Code] ....

However, I would like it to output;

Name
Description
Date
How complex is the structure?
The total value of assets?
The volume of transactions undertaken?
How was the client introduced?
Where does the Customer reside?

[Code] ....

The number of questions are unknown for each RiskReviewID and they can be added to in the future.

View 7 Replies View Related

Transact SQL :: Parse Unknown Number Of Data Elements To Multiple Lines

Jun 11, 2015

We are using a table that may give 1 to and unknown number of data elements (ie. years) .   How can we break this to show only three years in each row.  Since we don't know the number years we really won't know the number of rows needed.  Years are stored in their own table by line.  
 
car make year1 year2 year3
A   volare 1995 1996 1997
a   volare 1997   1998   1999
b toyat  1965    1966   1968

We can pivot out the first X# but we don't know how many lines so we don't know how many rows we will be creating.

View 8 Replies View Related

SQL Server 2008 :: How To Pivot Unknown Number Of Rows To Columns Using Data As Column Headers

Sep 10, 2015

I have a single table that consist of 4 columns. Entity, ParamName, ParamsValue and ParamiValue. This table stores normalized Late Fee related parameters for apartments. The Entity field contains a code that identifies the apartment complex. The ParamName in a textual field that contains the name of the parameter that the other 2 fields define the value for; ParamsValue and ParamiValue. If the Late Fee parameter (as named in ParamName is something numerical then the value for that parameter can be found in ParamiValue else its in ParamsValue.

I don't know if 'Pivot' is the correct term to use for describing what I am trying to do because I've looked at the Pivot examples and I don't see how that will work for this. Using the Table and data as provided below, how would I construct a query so that I get 1 row per Entity in which the columns are the ParamsValue or ParamiValue for the ParamName listed in the column header (for the query)?

Below is the DDL to create the table and populate it.

USE [DBA_UTIL]
CREATE TABLE [dbo].[PARAMEXAMPLE](
[Entity] [varchar](16) NULL,

[Code]....

View 4 Replies View Related

Unknown Members In Report Parameter Causes CONSTRAINED Flag Error In STRTOSET Function When NullProcessing Unknown Member

May 1, 2007

Hi,



I'm using MS Report Designer 2005 and have created a report that uses a cube, with a dimension set up to convert null values to unknown (nullProcessing = UnknownMember).



When I create a parameter using the checkbox in the graphical design mode's filter pane, Report Designer automatically sets the constrained flag, eg:

STRTOMEMBER(@DimOrganisationBUSADDRSTATE, CONSTRAINED).



When running the report and selecting the 'Unkown' value from the parameter list, the error 'the restrictions imposed by the CONSTRAINED flag in the STRTOSET function were violated' occurrs.



How can I prevent the constrained flag from being used, or am I doing something wrong with converting null values to 'Unknown'?



Thanks



View 10 Replies View Related

Drop Tables With Unknown Names And Unknown Quantity

Jul 20, 2005

This is what I want to do:1. Delete all tables in database with table names that ends with anumber.2. Leave all other tables in tact.3. Table names are unknown.4. Numbers attached to table names are unknown.5. Unknown number of tables in database.For example:(Tables in database)AccountAccount1Account2BinderBinder1Binder2Binder3.......I want to delete all the tables in the database with the exceptionof Account and Binder.I know that there are no wildcards in the "Drop Table tablename"syntax. Does anyone have any suggestions on how to write this sqlstatement?Note: I am executing this statement in MS Access with the"DoCmd.RunSQL sql_statement" command.Thanks for any help!

View 2 Replies View Related

How To Number Records / Duplicates Receiving Same Number

Feb 19, 2013

I have a large table of customers. I would like to add a column that contains an integer, unique to that customer. The trick is that this file contains many duplicate customers, so I want the duplicates to all have the same number between them.the numbers dont have to be sequential or anything, just like customers having the same one.

View 8 Replies View Related

Page Number &&amp; Records Number

Jun 20, 2006

1. how to show page number & total page number in report body?

2. how to show total records number?

View 25 Replies View Related

Specify The Number Of Records

Apr 26, 2001

Hi,
I want to the users to specify the number of TOPn records to be returned by the query.It has to be a query and not a stored proceedure.
Thanx

View 3 Replies View Related

How To Get Each Number Of Records...

Dec 2, 2006

HI EVERYBODY
This is my procedure
"
CREATE PROCEDURE SP_SAMPLE_SEARCH
@Title nvarchar(256)
AS

SELECT ID,Title,Price FROM [tbl_Sim] WHERE ([Title] LIKE '%' + @Title + '%') Order by Price desc
GO
"
I exec procedure and it returns 12 results with diffirents ID
and want to get these values 1,2,3....12
How do I get these...
I am a beginner.
Thanks for help..

View 6 Replies View Related

Get TOP Number Of Records

May 29, 2015

I'm using SQLCE. I'm using this sql statement:

sSQL = "Select Top (5) fldStatus,
Count(fldStatus) As CountOfSummaryItem From tbl_Records_DR GROUP BY
fldStatus;"

It gets the top 5 of fldStatus but I need the top 5 of CountOfSummaryItem.

View 2 Replies View Related

Number Of Affected Records

Feb 12, 2007

Okay..i have this problem ...i am using SQL server 2005 standard ,C#,VS2005
--i am inserting some record in DB .. using ExecuteNonQuery...i want to know how many records are getting inserted..so in my DB class i did something like this : numRecords = commandObject.ExecuteNonQuery() ,assuming  that ExecuteNonQuery returns the number of affected records.i am retriving this numOfRecords in my code behind and printing it but it always prints 1,even though more then one records are inserted.What is wrong here?
-i also have returnValue defiend like this.Could this tell me anything about how many records are inserted or affected during update,select ?if so,how?
cmd.Parameters.Add(new SqlParameter("@returnVal", SqlDbType.Int));
cmd.Parameters["@returnVal"].Direction = ParameterDirection.ReturnValue;
Please help me out with this.Thanks

View 14 Replies View Related

How To Count Number Of Records

Feb 26, 2008

hi
can anyone tell me how to count number of records(rows) in a table without using "COUNT" function.for practise iam trying to implement it through queries.

View 6 Replies View Related

Count Number Of Records

May 13, 2008

Using linq what would be the most efficient method of counting the number of users in the users table? 

View 2 Replies View Related

How Can I Now The RecordSource Number Of Records?

Dec 16, 2005

Hi...
I just begining to use the asp.net 2.0 and have tow littel problems... in my project the user makes a "list of problems on a house" when hi post the house number the page shoud to generete a master recod with a keynumber, the date an hour and the state of problems... and a form to insert a list of problems... but if the house dosn´t exist this forms are hidden... then i need to know the nomber of records that gets a recordsource if its more than cero show the forms else hiden it... if show the forms i need to store in a variable the keynumber to store it in the problem details table... ¿How i can khow the number of records of a RecordSource gets?... and ¿How I can store in a variable a field value retrived for a RecordSource?... I´m using VWD and SQL Express that means ADO.NET 2.0...
cheers.

View 1 Replies View Related

Total Number Of Records

Sep 27, 2001

Hi everbody,

I want find out Total number records in one table without using select statment.
Some body as told to me there is system table you can find total number of records. Any body give me systable name.
Thanks
Jack

View 2 Replies View Related

Total Number Of Records

Sep 27, 2001

Hi everbody,

I want find out Total number records in one table without using select statment.
Some body as told to me there is system table you can find total number of records. Any body give me systable name.
Thanks
Jack

View 1 Replies View Related

Getting Number Of Records Modified

Oct 20, 2004

Hi all

My manager ask me to provide him with the total number of records which have been added, deleted or modified on a certain database in SQL Server 2000 during the month of September. Is there away to get that information from the transaction log or by any how?

please some one guide me how to do that?

Your help is highly appreciated

View 8 Replies View Related

Selecting A Certain Number Of Records?

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

My Number Of Records Are Different From Views

Apr 20, 2008

Why is it my number of records are different from my view. this are the following code that that i used in my code and in my view.

my code in my program: this code show all the records i know

If iConn.State = ConnectionState.Open Then iConn.Close()
iConn.Open()
Dim rsBills As New Data.DataSet
rsBills = New DataSet
Dim daBills As New SqlDataAdapter
daBills = New SqlDataAdapter
rsBills.Clear()
Dim cmBills As New SqlCommand
cmBills = iConn.CreateCommand ' "Select U_Code, U_Name, U_Level, P_Word From EPassword ",
cmBills.CommandText = "Select OR_no, Billing_mo From dbo.vwBilling Where Month(dbo.vwBilling.Billing_mo)= " & Month(Me.dtto.Value) & " And Year(dbo.vwBilling.Billing_mo) = " & Year(Me.dtto.Value) & " ORDER BY OR_no "

daBills.SelectCommand = cmBills
rsBills.AcceptChanges()
rsBills.Clear()
daBills.Fill(rsBills, "Bills")
Me.DataGridView1.DataSource = Nothing
Me.DataGridView1.DataSource = rsBills.Tables("Bills")

my code in views:

SELECT OR_no, Billing_mo, Account_no, Name, Address, Cno, Pres_read, Mprev_read, Sub_read, Pres2, Prev2, SRead2, Mtr_cons, Amount, NPC, Dmem,
Cmem, Tot_bill, D_Pmnt, Class, Newbill, Prd_fr, Prd_to, Type_Pmnt, Type_Date, Type_Docs, wtax
FROM dbo.Billing


hope you can help me guys

View 1 Replies View Related

Limit On Number Of Records

Apr 21, 2008

is there a limitations of number of records that shows in the table when you use show data table?

View 1 Replies View Related

DISTINCT And Number Of Records

Mar 19, 2008

Wondering if there is a way to do this...

I want to select the DISTINCT user name from each record in a table, and then have another field tell me how many records it found..

is there any way to do this with SQL?


SELECT DISTINCT user_Name FROM table ORDER BY user_Name


is what I have now....


need something that will return:

user_Name numRecs
bob 3
fred 6
sam 1
linda 2

View 1 Replies View Related

Getting The Number Of Records With Like Values

Jun 14, 2006

I have a resultset that looks something like this:

Anzahl users_statdata_hobbies
---------------------
499 Andere
266 Essen
60 Essen,Andere
127 Essen,Musik
10 Essen,Musik,Party,Andere
30 Essen,Party
4 Essen,Party,Andere
51 Kunst
4 Kunst,Andere
13 Kunst,Essen
4 Kunst,Essen,Andere

I get this with this query which might be altered somehow:



SELECT COUNT(*) AS Anzahl, users_statdata_hobbies

FROM vgetAuswertung2

GROUP BY users_statdata_hobbies

ORDER BY users_statdata_hobbies

Of course this is not normalized but I can't change this.

Nevertheless I need to get the full number of each Hobby and not only the combination of them.

So instead or in addition to the existing recordset I need e.g

357 Essen which ist the sum of all records containing 'Essen' in the above example

The list of individual hobbies is defined therefor I could loop through the list manually and search for 'WHERE Hobbies LIKE '%ESSEN%' and count but since it's quiet a big resultset and there are several other similar tasks already I'm looking for a more performant way and I'm sure it could be done in SQL directly.

Any ideas someone?

View 4 Replies View Related

Restricting Number Of Records

May 19, 2006

I want to restrict the number of records coming from an OLEDB source. I have 500 records in my source table and I want to process one record at a time

I have I set the MaxBufferRows parameter to 1and it l sends 8 records from OLEDB source

Any help is appreciated.

View 9 Replies View Related

How Do I Put Records Number In Union

Dec 21, 2007



Hi i have sql statement like this :

SELECT row_number() over (ORDER by a.empid) as rec_num, empname
FROM employee_a
UNION
SELECT row_number() over (ORDER by a.empid) as rec_num, empname
FROM employee_b

the problem is the rec_num repeat for each statement like this :




rec_num empname

1 john
2 maggy
1 lee
2 mary
3 louis

How do i make the rec_num continue for the next statement after union.

View 1 Replies View Related

Sequence Number For Records

Nov 15, 2007

Hi...

I have Sql statement more like this

SELECT row_number() over (ORDER by a.employeeID) as rec_num, a.* FROM EmployeeA a
UNION
SELECT row_number() over (ORDER by a.employeeID) as rec_num, a.* FROM EmployeeB a


rec_num employeeID employeeName employeeDepartment


1 777 Mike HR
2 888 Susy HR
1 111 Smith TECH
2 222 John TECH
3 333 Lenny TECH



How do i get sequence number for all of this records. The rec_num reset for every statement. I want the records numbering for second statement continue from first statement so that it can be like this :

rec_num employeeID employeeName employeeDepartment


1 777 Mike HR
2 888 Susy HR
3 111 Smith TECH
4 222 John TECH
5 333 Lenny TECH

View 4 Replies View Related

Number Of Records In SQLDataSource/GridView

Aug 21, 2006

What is the easiest way to obtain number of records in SQLDataSource (using select statement)/GridView. All that I've found in forums seems to be very difficult for such trivial task... Thank you!

View 4 Replies View Related

Search For Records That Begins With A Number (0-9)?

Aug 2, 2007

Hi all,For now I can use this code to display all the records that begins with a Letter:(WHERE SONG_TITLE LIKE @SONG_TITLE + '%') Now how do I search for records that begins with a number (from 0-9), as an add-on to the above query?Thank you very much,Kenny. 

View 6 Replies View Related

Obtaining The Number Of Records In A SqlDataReader

Feb 26, 2004

Can anyone tell me how I can obtain the number of records returned in a sqlDataReader recordset?

View 8 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved