SQL Math Functions With COUNT() - Can Anyone Help, Please?

Mar 28, 2007

I have been trying to make a database that counts up and down votes (like eBay ratings or reddit votes).  I think (hope) I have got the database design right.

I know that you can perform math functions in SQL, but I want to use two COUNT()s from the same table and subtract one (the down votes) from the other (the up votes).

I have been learning ASP.NET 2.0 and it's going well, but I really need help with this.  I asked a question on this forum before and the answers were great and really helpful.

If anyone can help that would be great.  Thank you.

Jack.

View 3 Replies


ADVERTISEMENT

Math Functions

Mar 31, 2006

Hi,How to find the list of SQL math functions in SQL Server 2005?ThanksKai

View 2 Replies View Related

Accumulating Data Derived From COUNT Functions

Nov 10, 2004

Hi all,

I'm in a situation where I need to accumulate values from several columns in each of the rows returned in a result set and to then display each accumulation value for each row at the end of each row.

For example, if I had the following...

------------------------------------------------------
name - car - van - bus - total
------------------------------------------------------
Terry - 55 - 34 - 12 - 101
John - 01 - 23 - 05 - 029
etc etc
------------------------------------------------------

Where 'total' column is an accumuliation of the 'car', 'van', and 'bus' columns. The values for the columns 'car', 'van', and 'bus' are all values that have been derived from COUNT function. So what I want is to somehow genarate the values for the 'total' column (car + van + bus).

Now I have tried the following SQL, but to no avail


Code:

SELECT pveh.csign, pveh.name1 AS [Driver], COUNT(pveh.name1) AS Car, COUNT(pveh.name2) AS Van, SUM(COUNT(pveh.name1) + SUM(COUNT(pveh.name2))
FROM planvehicles AS pveh

... and I also tried...

SELECT pveh.csign, pveh.name1 AS [Driver], COUNT(pveh.name1) AS Car, COUNT(pveh.name2) AS Van, SUM(Car + Van)
FROM planvehicles AS pveh



Thanks

Tryst

View 12 Replies View Related

Math Or Text

Dec 13, 2006

in the below sql why is    year(classdate)  " + " a " + " MONTH(classdate)  a math command giving me   2006 - 12 = 167
and not "2006/12" as text? please help me
 cmdGetCat = New SqlDataAdapter("SELECT DISTINCT   year(classdate)  " + " a " + " MONTH(classdate) AS  monthcode  FROM  dbo.classT INNER JOIN dbo.classgiven ON dbo.classT.classcode = dbo.classgiven.classcode WHERE (dbo.classT.discount = '-1') AND  (dbo.classT.coned IS NOT NULL) ", conNorthwind)
 
 

View 4 Replies View Related

Sql Math Question

Nov 18, 2007

How do i update a sql table so that the result cannot be less than zero?for example, lets say I have the column "Number"I have a sql update statement that subtracts 1 from number:"Update oTable SET Number = (Number - 1)"Except that Number cannot be less than zero.  Is there a way to do this in sql statement so that I don't have to have a select statement just to check that Number is greater than zero to begin with? Thanks 

View 4 Replies View Related

Doing Math On Tables

Oct 26, 2004

Hello everyone:

I have a database for one of my websites, a picture rating site. Anyways, right now there are quicte a few tables, and I was wondering how to give the server a break and was wondering if this was possible:

Basicly I have a members table, and a votes table. Members will rate other users pcitures on a scale of one to ten, then the votes will be inserted into the votes table. The only problem with this is that calcuating all the votes a user has can put a straing on the server. I was wondering if it would be possible to create a math column in the members table that would automaticly figure out the users average and having it stored in a field in the members table, so all I would have to do is query the members average located in the mebers table, rather than tallying all the votes in the votes table for each member.

Hope this makes sense, a tutorial or any suggestions would be great!

Thanks

View 1 Replies View Related

Some Math Logics

Feb 2, 2004

I have 2 questions.

1) Lets say we have a table

CREATE TABLE TEST
(
N INT
)

These table have 10 records - the numbers from 1 to 10.

I need 1 query ONLY which will update the table and make it with 100 records - the numbers from 1 to 100.

2) How with 1 query ONLY i have select only the prime numbers

View 4 Replies View Related

Date Math In SQL - How To Do?

Jan 16, 2006

I have some dates stored in a field named "visit"

In a select they show as the format:
2005-07-28 10:45:00.000


So I need to write a query that will select Visits that are more than 90 days old. I thought it might be something simple like:

Select * from patientVisit where ((getdate())-Visit>90)

But that is pulling all visits not just 90 day old ones.

How do I pull the current date/time and compute the cutoff date time that would be 90 days prior for my selection Where clause?

Thanks

View 3 Replies View Related

Math Between Columns

Jun 30, 2006

I need to create a new column where I subtract one column by another.
I've been looking fo that for a while now, can someone explain how to do this?

View 7 Replies View Related

Math Error

Nov 23, 2006

select convert(float,'1.2334e+006')1233400.0select convert(decimal(20,2),'1.2334e+006')Server: Msg 8114, Level 16, State 5, Line 1Error converting data type varchar to numeric.can I set some options arithabort etc to have a workaround to thisproblem?Thanks.

View 3 Replies View Related

Math Notation In Db?

Dec 1, 2007

I'm not a professional dba or dbd, but I'm proficient in the basics ofdatabase design and sql. I want to create a database of mathdefinitions, and I'm wondering how one would go about creating adatabase that contains mathematical notation (and I'm not just talkingabout basic symbols where I could get away with ascii code). I needto be able to insert a wide variety of mathematical expressions, fromfractions to integrals, into fields (just like you can enter in-linemath symbols in MS Word using equation editor). I have no clue how togo about this. Is it a matter of developing certain programmingskills/languages? Would such a capabliltiy be proprietary (dbms-specific)? Is it possible at all? Any help would be appreciated.Thank you.

View 3 Replies View Related

Math Function

Jul 20, 2005

Hi AllI'm trying to find a math function (if it exists) in SQL Server. If itdoesnt exist, then maybe someone can tell me what its called so I cando a bit more reading on itBasically I want to do this:Parameter Components1 12 23 1, 24 45 1, 46 2, 47 3, 48 89 1, 8and so onI'd like to be able to call a function and it would return true orfalse like sofunctionname(1, 9) = trueso 1 is a component of 9functionname(2, 9) = falseso 2 is not a component of 9functionname(4, 5) = trueso 4 is a component of 5If anyone could tell me if it exists in C#, VB.NET, VB6 or VBScript,I'd appreciate it!Thanks in advanceSam

View 2 Replies View Related

Date Math

Jan 9, 2008

Below is my table layout, query, and results. I need to perform some date math to display how much time is elapsed between locations as patients are checked into each care_unit. I believe I could use the unique careunit_key but am not sure how to go about this.

[srm].[CDMAB_CAREUNITS]

[CAREUNIT_KEY] [decimal](37, 0) NOT NULL,

[EPISODE_KEY] [decimal](38, 0) NULL,

[CARE_UNIT] [char](20) NULL,

[ROOM_NO] [char](5) NULL,

[BED_NO] [char](5) NULL,

[DATE_IN] [datetime] NULL,

[TIME_IN] [char](6) NULL


select

cu.careunit_key,

cu.care_unit,

convert(nvarchar,e.ADMISSION_DATE, 101) as Admit_Date,

convert(nvarchar,e.EPISODE_DATE, 101) as Discharge_Date,

convert(nvarchar,cu.date_in,101) as date_in,

substring(cu.time_in, 1,5) as time_in,

convert(nvarchar,cu.date_in,101) +

convert(datetime,substring(cu.time_in, 1,5)) as date_time_in

FROM srm.episodes e

inner join srm.CDMAB_CAREUNITS cu on cu.episode_key = e.episode_key

inner join srm.item_header ih on ih.item_key = e.episode_key

inner join srm.patients p on p.patient_key = ih.logical_parent_key

where e.account_number = '11111777777'














CAREUNIT_KEY
CARE_UNIT
ADMIT_DATE
DISCHARGE_DATE
DATE_IN
TIME_IN
DATE_TIME_IN

1488831
3
12/10/2007
12/11/2007
12/10/2007
3:00
12/10/07 3:00

1498258
S4C
12/10/2007
12/11/2007
12/10/2007
5:54
12/10/07 5:54

1498406
SREC
12/10/2007
12/11/2007
12/10/2007
11:05
12/10/07 11:05

1498472
S6W
12/10/2007
12/11/2007
12/10/2007
12:37
12/10/07 12:37








View 3 Replies View Related

Doing Math With Cells

Apr 19, 2007

Good day all

Does anyone know if there is such a quary that can be written which would add up(or any math functions) a line of cells (on different rows) similar to that of working with a excel document?

If so please steer me towards the correct syntax for this.

Regards

Rob

View 1 Replies View Related

Date Math

Mar 12, 2008

Hi,

I have a column coming from DB2. It is the time is stored as 6 decimals of a second. So the value I got coming in is 44846(DT_I8), which needs to be divided by 60 to get minutes (747 minutes remainder 26 seconds). Then divide 747 by 60 to get 12 hours remainder 27 minutes. Thus the time is 12:27:26.

I have got a dervived column doing (DT_R8)(SUBSTRING((DT_WSTR,8)PSCCLOGTIM,1,5)) / 60 but the answer I am getting out is 747.433333. Close, but not close enough. Now I assume my problem has something to do with the Math being done on actual numbers not Time based numbers.

Anyone got any ideas on where I am going wrong and what the expression should look like?

View 11 Replies View Related

Performing Math Problem

Nov 19, 2003

I need to perform some division on the results of two alias columns that perform counts in a query. What is the best way to do this?

View 7 Replies View Related

Math Is Driving Me Nuts

Jul 20, 2005

The business rule is, the sales manager is commissioned on the avg. numberof appointments set up per salesrep per day during the month.I have 2 tables: The UserLog table records only 1 entry per day per user(salesrep). This will log how many salesreps worked a particular day. Thesecond table logs any appointments set up.UserLog: ID, UserName, EnteredTimeAppointment: ApptID, EnteredTime, ApptDateI figured that, for a given date ranged, I could1. sum the number of appointments2. sum the number of days worked2. sum the salesreps / number of days = avg number of salesreps per day3. number of appointments / avg number of salesreps per day = avg numberof appointments per sales repBut this logic is flawed. If I average out every day and then take anaverage of this daily average, I get a different result. Any ideas on howto best solve this problem?Thanks.

View 7 Replies View Related

Math - Division Question..

Dec 6, 2007

To set the stage, Tables are set up as such for this question:
-----------

Table: Answers
ID - Integer - Auto
Answer - Integer
QuestionID - Integer - FK from the QuizMaster table
StudentID - Integer - FK from the Students table

Table: QuizMaster

ID - Integer - Auto
Answer - Integer

Table: Students
ID - Integer - Auto
StudentName - Varchar(50)
----------
I would like to have an either a sql statement (1st) or a stored procedure (2nd) that would give me the percent correct for each student on the test.

In Access I could cheat and use this:



Code BlockSELECT Students.StudentName,
Count(Students.StudentName) AS TotalCorrect,
(SELECT Count(QuizMaster.ID) FROM QuizMaster;) AS TotalQuestions,
([TotalCorrect])/([TotalQuestions])*100 AS PercentValue
FROM (Answers INNER JOIN Students

ON Answers.StudentID = Students.ID)
INNER JOIN QuizMaster
ON (Answers.Answer = QuizMaster.Answer)
AND (Answers.QuestionID = QuizMaster.ID)
GROUP BY Students.StudentName
ORDER BY Students.StudentName, PercentValue;

Which is composed of the following...







Code Block

SELECT Students.StudentName,


Count(Students.StudentName) AS TotalCorrect
FROM (Answers INNER JOIN Students

ON Answers.StudentID = Students.ID)
INNER JOIN QuizMaster
ON (Answers.Answer = QuizMaster.Answer)
AND (Answers.QuestionID = QuizMaster.ID)


GROUP BY Students.StudentName;


SELECT Count(QuizMaster.ID) AS TotalQuestions
FROM QuizMaster;


([TotalCorrect])/([TotalQuestions])*100 AS PercentValue


But... that wont fly in SQL Server...What would work without using temp tables?
What would be the EASIEST way to do this?

Another way someone suggested is:




Code BlockCREATE PROCEDURE GetStudentGradeByID @StudentID Integer

AS

BEGIN


DECLARE @TotalQuestionsAsked as Integer;
DECLARE @StudentName as VarChar(50);
DECLARE @QuestionsCorrect as Integer;
DECLARE @PercentCorrect as Float;

set @TotalQuestionsAsked = select COUNT(*)FROM QuizMaster;
set @StudentName = select StudentName from Students where ID = @StudentID;

set @QuestionsCorrect = select count(Answers.ID) from Answers LEFT JOIN QuizMaster on Answers.QuestionID = QuizMaster.ID where StudentID = @StudentID AND QuizMaster.Answer = Answers.Answer;
set @PercentCorrect = (CAST (@QuestionsCorrect AS FLOAT) / CAST (@TotalQuestionsAsked AS FLOAT)) * 100.0;

select @QuestionsCorrect as TotalCorrect, @StudentName as Student, @TotalQuestionsAsked as NumQuestions, @PercentCorrect as CorrectPct;

END


But I need this as a datasource for a datagrid that would show all students etc... so using a parameter isn't really what I want.
So... could a stored procedure work for this?

View 14 Replies View Related

Please Help Me W/ My Query, Simple Math!

Jan 29, 2008

hi,

declare @query1 varchar(1000)
declare @query2 varchar(1000)
set @query1 = 'select count(*) from table1'
set @query2 = 'select count(*) from table2'

select @query1 - @query2

basically, i want to show the difference of this 2 select statements.. how do i do it?

thanks in advance!

View 5 Replies View Related

Interesting Math In A T-SQL Query

Oct 2, 2007


The value in the table of one DB is 17869 sq. ft. Now to insert this value in a new table of other database the reporting basis is 1000 i.e I need to do 17869/1000 = 17.8 so I have to take the value as 18. Another thing to be kept in mind is the value in the new table should have leading Zeroes. If the value is 18 it should be displayed as 0000018 ( data type in new table is Varchar(7) and in old table char (9) ). What can be the best way to implement this??

View 8 Replies View Related

SQL Server 2005: CLR Functions Vs SQL Functions

May 26, 2006

I was playing around with the new SQL 2005 CLR functionality andremembered this discussion that I had with Erland Sommarskog concerningperformance of scalar UDFs some time ago (See "Calling sp_oa* infunction" in this newsgroup). In that discussion, Erland made thefollowing comment about UDFs in SQL 2005:[color=blue][color=green]>>The good news is that in SQL 2005, Microsoft has addressed several of[/color][/color]these issues, and the cost of a UDF is not as severe there. In fact fora complex expression, a UDF in written a CLR language may be fasterthanthe corresponding expression using built-in T-SQL functions.<<I thought the I would put this to the test using some of the same SQLas before, but adding a simple scalar CLR UDF into the mix. The testinvolved querying a simple table with about 300,000 rows. Thescenarios are as follows:(A) Use a simple CASE function to calculate a column(B) Use a simple CASE function to calculate a column and as a criterionin the WHERE clause(C) Use a scalar UDF to calculate a column(D) Use a scalar UDF to calculate a column and as a criterion in theWHERE clause(E) Use a scalar CLR UDF to calculate a column(F) Use a scalar CLR UDF to calculate a column and as a criterion inthe WHERE clauseA sample of the results is as follows (time in milliseconds):(295310 row(s) affected)A: 1563(150003 row(s) affected)B: 906(295310 row(s) affected)C: 2703(150003 row(s) affected)D: 2533(295310 row(s) affected)E: 2060(150003 row(s) affected)F: 2190The scalar CLR UDF function was significantly faster than the classicscalar UDF, even for this very simple function. Perhaps a more complexfunction would have shown even a greater difference. Based on this, Imust conclude that Erland was right. Of course, it's still faster tostick with basic built-in functions like CASE.In another test, I decided to run some queries to compare built-inaggregates vs. a couple of simple CLR aggregates as follows:(G) Calculate averages by group using the built-in AVG aggregate(H) Calculate averages by group using a CLR aggregate that similatesthe built-in AVG aggregate(I) Calculate a "trimmed" average by group (average excluding highestand lowest values) using built-in aggregates(J) Calculate a "trimmed" average by group using a CLR aggregatespecially designed for this purposeA sample of the results is as follows (time in milliseconds):(59 row(s) affected)G: 313(59 row(s) affected)H: 890(59 row(s) affected)I: 216(59 row(s) affected)J: 846It seems that the CLR aggregates came with a significant performancepenalty over the built-in aggregates. Perhaps they would pay off if Iwere attempting a very complex type of aggregation. However, at thispoint I'm going to shy away from using these unless I can't find a wayto do the calculation with standard SQL.In a way, I'm happy that basic SQL still seems to be the fastest way toget things done. With the addition of the new CLR functionality, Isuspect that MS may be giving us developers enough rope to comfortablyhang ourselves if we're not careful.Bill E.Hollywood, FL------------------------------------------------------------------------- table TestAssignment, about 300,000 rowsCREATE TABLE [dbo].[TestAssignment]([TestAssignmentID] [int] NOT NULL,[ProductID] [int] NULL,[PercentPassed] [int] NULL,CONSTRAINT [PK_TestAssignment] PRIMARY KEY CLUSTERED([TestAssignmentID] ASC)--Scalar UDF in SQLCREATE FUNCTION [dbo].[fnIsEven](@intValue int)RETURNS bitASBEGINDeclare @bitReturnValue bitIf @intValue % 2 = 0Set @bitReturnValue=1ElseSet @bitReturnValue=0RETURN @bitReturnValueEND--Scalar CLR UDF/*using System;using System.Data;using System.Data.SqlClient;using System.Data.SqlTypes;using Microsoft.SqlServer.Server;public partial class UserDefinedFunctions{[Microsoft.SqlServer.Server.SqlFunction(IsDetermini stic=true,IsPrecise=true)]public static SqlBoolean IsEven(SqlInt32 value){if(value % 2 == 0){return true;}else{return false;}}};*/--Test #1--Scenario A - Query with calculated column--SELECT TestAssignmentID,CASE WHEN TestAssignmentID % 2=0 THEN 1 ELSE 0 END ASCalcColumnFROM TestAssignment--Scenario B - Query with calculated column as criterion--SELECT TestAssignmentID,CASE WHEN TestAssignmentID % 2=0 THEN 1 ELSE 0 END ASCalcColumnFROM TestAssignmentWHERE CASE WHEN TestAssignmentID % 2=0 THEN 1 ELSE 0 END=1--Scenario C - Query using scalar UDF--SELECT TestAssignmentID,dbo.fnIsEven(TestAssignmentID) AS CalcColumnFROM TestAssignment--Scenario D - Query using scalar UDF as crierion--SELECT TestAssignmentID,dbo.fnIsEven(TestAssignmentID) AS CalcColumnFROM TestAssignmentWHERE dbo.fnIsEven(TestAssignmentID)=1--Scenario E - Query using CLR scalar UDF--SELECT TestAssignmentID,dbo.fnIsEven_CLR(TestAssignmentID) AS CalcColumnFROM TestAssignment--Scenario F - Query using CLR scalar UDF as crierion--SELECT TestAssignmentID,dbo.fnIsEven_CLR(TestAssignmentID) AS CalcColumnFROM TestAssignmentWHERE dbo.fnIsEven(TestAssignmentID)=1--CLR Aggregate functions/*using System;using System.Data;using System.Data.SqlClient;using System.Data.SqlTypes;using Microsoft.SqlServer.Server;[Serializable][Microsoft.SqlServer.Server.SqlUserDefinedAggregate (Format.Native)]public struct Avg{public void Init(){this.numValues = 0;this.totalValue = 0;}public void Accumulate(SqlDouble Value){if (!Value.IsNull){this.numValues++;this.totalValue += Value;}}public void Merge(Avg Group){if (Group.numValues > 0){this.numValues += Group.numValues;this.totalValue += Group.totalValue;}}public SqlDouble Terminate(){if (numValues == 0){return SqlDouble.Null;}else{return (this.totalValue / this.numValues);}}// private accumulatorsprivate int numValues;private SqlDouble totalValue;}[Serializable][Microsoft.SqlServer.Server.SqlUserDefinedAggregate (Format.Native)]public struct TrimmedAvg{public void Init(){this.numValues = 0;this.totalValue = 0;this.minValue = SqlDouble.MaxValue;this.maxValue = SqlDouble.MinValue;}public void Accumulate(SqlDouble Value){if (!Value.IsNull){this.numValues++;this.totalValue += Value;if (Value < this.minValue)this.minValue = Value;if (Value > this.maxValue)this.maxValue = Value;}}public void Merge(TrimmedAvg Group){if (Group.numValues > 0){this.numValues += Group.numValues;this.totalValue += Group.totalValue;if (Group.minValue < this.minValue)this.minValue = Group.minValue;if (Group.maxValue > this.maxValue)this.maxValue = Group.maxValue;}}public SqlDouble Terminate(){if (this.numValues < 3)return SqlDouble.Null;else{this.numValues -= 2;this.totalValue -= this.minValue;this.totalValue -= this.maxValue;return (this.totalValue / this.numValues);}}// private accumulatorsprivate int numValues;private SqlDouble totalValue;private SqlDouble minValue;private SqlDouble maxValue;}*/--Test #2--Scenario G - Average Query using built-in aggregate--SELECT ProductID, Avg(Cast(PercentPassed AS float))FROM TestAssignmentGROUP BY ProductIDORDER BY ProductID--Scenario H - Average Query using CLR aggregate--SELECT ProductID, dbo.Avg_CLR(Cast(PercentPassed AS float)) AS AverageFROM TestAssignmentGROUP BY ProductIDORDER BY ProductID--Scenario I - Trimmed Average Query using built in aggregates/setoperations--SELECT A.ProductID,CaseWhen B.CountValues<3 Then NullElse Cast(A.Total-B.MaxValue-B.MinValue ASfloat)/Cast(B.CountValues-2 As float)End AS AverageFROM(SELECT ProductID, Sum(PercentPassed) AS TotalFROM TestAssignmentGROUP BY ProductID) ALEFT JOIN(SELECT ProductID,Max(PercentPassed) AS MaxValue,Min(PercentPassed) AS MinValue,Count(*) AS CountValuesFROM TestAssignmentWHERE PercentPassed Is Not NullGROUP BY ProductID) BON A.ProductID=B.ProductIDORDER BY A.ProductID--Scenario J - Trimmed Average Query using CLR aggregate--SELECT ProductID, dbo.TrimmedAvg_CLR(Cast(PercentPassed AS real)) ASAverageFROM TestAssignmentGROUP BY ProductIDORDER BY ProductID

View 9 Replies View Related

Make Math Operations With DateTime

Sep 23, 2007

hi,
how can i make mathematical operations with the DateTime format from thw Sql? -- this is the format 9/6/2007 11:09:00 PM --
how can i substract 30 days from that date and know the resulting one?
if i have two dates, how can i know what number of hours and minutes are between them (if they are fewer than 24), or what number of days and hours and minutes are (if the difference is grater than 24 hours)
please help me, thanks

View 2 Replies View Related

Math Over Datetime In Varchar Format??

Jun 17, 2008

Hello,

I have this column of time values:
00:00:03.3592675
00:00:00
00:00:03.8592515
00:00:03.6873820
00:00:03.8436270
00:00:03.3436430

It is in varchar format. I tried converting it to datetime but get an invalid format error message.

How can I sum up these values and average them out?

Thanks!

--PhB

View 1 Replies View Related

Evaluating Varchar String With Math

Mar 5, 2008

In reference to this thread:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50392

madhivanan asks for sample table data to avoid using a cursor. I could really use this, so here is the table



CREATE TABLE #T (
FORMULA VARCHAR(15),
ANSWER decimal(15,8)
)
INSERT INTO #T SELECT '1', NULL
INSERT INTO #T SELECT '1.0 + 2', NULL
INSERT INTO #T SELECT '1/2', NULL
INSERT INTO #T SELECT '1/2+2', NULL
INSERT INTO #T SELECT '1/(2+2)',NULL
INSERT INTO #T SELECT '3*7.5', NULL
INSERT INTO #T SELECT '3/2*.6-2', NULL
INSERT INTO #T SELECT '(1-1)', NULL

SELECT * FROM #T

-- RUN THE MATH FUNCTIONS, UPDATE THE TABLE'S ANSWER COLUMN WITH THE ANSWER

SELECT * FROM #T

DROP TABLE #T


I would expect this output:

FORMULA ANSWER
====================
1 NULL
1.0 + 2 NULL
1/2 NULL
1/2+2 NULL
1/(2+2) NULL
3*7.5 NULL
3/2*.6-2 NULL

FORMULA ANSWER
====================
1 1.00000000
1.0 + 2 3.00000000
1/2 0.50000000
1/2+2 2.50000000
1/(2+2) 0.25000000
3*7.5 22.50000000
3/2*.6-2 -1.10000000
(1-1) 0.00000000


Any help appreciated, thanks,

View 9 Replies View Related

Pseudocode To SQL Stored Proc Math Operation

Jan 30, 2006

How do i implement this pseudocode in a SQL stored proc?

In my stored proc, intDS and intSS are the corresponding locally declared variables: @cnt1 and @cnt2 (both are int's).

double intRating = 0;
if (intDS != 0)
intRating = ((intDS - intSS ) / intDS) * 100;
if (intRating < 0)
intRating = 0;
intRating = RoundUpDown(intRating);

The last line should round up or downd the decimal value, if it has decimals, to the next round/whole number... e.g. 28.4352635 to 28.

Thank you!

View 2 Replies View Related

Applied Math Problem - Creating A Cut List

Jan 28, 2008

I realize this gets into business logic, but a DB based solution might be best. Possibly some pre-calculated measurement tables.

Business problem: Creating a cut list for a window covering (blinds) system. It's preferably a fast calculation I could execute while the user awaits "order confirmation and pricing". A .5 second delay per order would be acceptable.

An order can have unlimited number of line items, but typically between 1 and 20 (number of windows in a single house).

(For this problem) the raw material is man-made, and therefore is always the same length for a particular pattern/color (take 12' for this example; we stock patterns in 9', 12', or 16' but it's always the same for a given pattern/color). I need to tell the cutters how to use the rawmaterial with minimal waste. Note: The saw blade takes 1/16th inch.

For each line item; I have pre-calculated the exact cut size and number of slats. Measurements are in inches at 1/8 (.125) inch increments. The length of raw material length we stock for this pattern is an easy link.

The goal is to average less than 6 inches waste per 12' piece of raw material.

Example order:

5 line items for pattern/color FAUX/white, stocked in 12' lengths.

Line 1: 34 slats at 35.125 inches.
Line 2: 36 slats at 36.875 inches.
Line 3: 50 slats at 42 inches.
Line 4: 55 slats at 70 inches.
Line 5: 52 slats at 30 inches.

The resulting cut-list-workorder would evaluate all lines together and tell them how many 12' slats to pull and how to cut them with minimal material waste.


My question:

I'm left wondering if a database style pre-populated answer list (or some other database based solution) might be a lot faster and simpler than some chess-style complex trial-and-error array based VB algorythm (that I haven't even begun to imagine how to write). If so; how would it look?

In addition; the cutters get something like $10/hr so we can't make it too complex. I'd rather waste a little material and avoid undue confusion, but not much. With $5+ million in this material per year, excess waste can really add up. Imagine the difference between 12% and 15% waste. It's an area worth investing in.

Sorry; I know it's not a simple question. Someone might find it interesting enough to solve, or at least provide hope for a DB solution. At present; I just can't imagine it.

View 3 Replies View Related

Doing Math Across Table Columns, Dealing With NULL

Oct 20, 2005

Christine the Pharmacist writes "Please pardon as I am not horribly advanced with SQL...

Using SQL Server 2000, Windows 2000, Service pack 4

I'm trying to figure out marketshares for "preferred" products. I have a table put together by hospital and month of medication use with the totals of each drug dispensed in columns as well.
(example table below)


Hospital Month Drug A Drug B Drug C Drug D
A 7 5 10 58 73
B 7 NULL 26 98 43
etc.


** Drug C and Drug D are the preferred drugs

I'm getting correct preferred % in all cases except when a value is NULL (result is NULL). I'm using an aggregate (sum), which should ignore NULLs, but it ignores NULLs within a column, and not ignoring across columns. I've tried setting concat_null_yields_null off and I'm still getting NULL (since I'm using the plus sign).

This is my admittedly confused select statement, suspect this is where my problem lies (problems with saying "sum", but using "+" as well?):

select a.Hospital,a.month,convert(float,sum(c.Drug_C+d.Drug_D))/convert(float,sum(a.Drug_A+b.Drug_B+
c.Drug_C+d.Drug_D)) as preferred_share

Thanks for any advice!"

View 4 Replies View Related

Transaction Count After EXECUTE Indicates That A COMMIT Or ROLLBACK TRANSACTION Statement Is Missing. Previous Count = 1, Current Count = 0.

Aug 6, 2006

With the function below, I receive this error:Error:Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing. Previous count = 1, current count = 0.Function:Public Shared Function DeleteMesssages(ByVal UserID As String, ByVal MessageIDs As List(Of String)) As Boolean        Dim bSuccess As Boolean        Dim MyConnection As SqlConnection = GetConnection()        Dim cmd As New SqlCommand("", MyConnection)        Dim i As Integer        Dim fBeginTransCalled As Boolean = False
        'messagetype 1 =internal messages        Try            '            ' Start transaction            '            MyConnection.Open()            cmd.CommandText = "BEGIN TRANSACTION"            cmd.ExecuteNonQuery()            fBeginTransCalled = True            Dim obj As Object            For i = 0 To MessageIDs.Count - 1                bSuccess = False                'delete userid-message reference                cmd.CommandText = "DELETE FROM tblUsersAndMessages WHERE MessageID=@MessageID AND UserID=@UserID"                cmd.Parameters.Add(New SqlParameter("@UserID", UserID))                cmd.Parameters.Add(New SqlParameter("@MessageID", MessageIDs(i).ToString))                cmd.ExecuteNonQuery()                'then delete the message itself if no other user has a reference                cmd.CommandText = "SELECT COUNT(*) FROM tblUsersAndMessages WHERE MessageID=@MessageID1"                cmd.Parameters.Add(New SqlParameter("@MessageID1", MessageIDs(i).ToString))                obj = cmd.ExecuteScalar                If ((Not (obj) Is Nothing) _                AndAlso ((TypeOf (obj) Is Integer) _                AndAlso (CType(obj, Integer) > 0))) Then                    'more references exist so do not delete message                Else                    'this is the only reference to the message so delete it permanently                    cmd.CommandText = "DELETE FROM tblMessages WHERE MessageID=@MessageID2"                    cmd.Parameters.Add(New SqlParameter("@MessageID2", MessageIDs(i).ToString))                    cmd.ExecuteNonQuery()                End If            Next i
            '            ' End transaction            '            cmd.CommandText = "COMMIT TRANSACTION"            cmd.ExecuteNonQuery()            bSuccess = True            fBeginTransCalled = False        Catch ex As Exception            'LOG ERROR            GlobalFunctions.ReportError("MessageDAL:DeleteMessages", ex.Message)        Finally            If fBeginTransCalled Then                Try                    cmd = New SqlCommand("ROLLBACK TRANSACTION", MyConnection)                    cmd.ExecuteNonQuery()                Catch e As System.Exception                End Try            End If            MyConnection.Close()        End Try        Return bSuccess    End Function

View 5 Replies View Related

T-SQL (SS2K8) :: XQuery Syntax To Evaluate Math Formula

Feb 25, 2015

I want to evaluate a math formula inside of a function, so I can't use dynamic SQL.

I found that the query on an XML-variable with a literal works well.

DECLARE @sParsedFormula varchar(200);
DECLARE @xFormula xml;
SET @xFormula = '';
SET @sParsedFormula = '1+2';
SELECT @xFormula.query('3+3') , @xFormula.query('sql:variable("@sParsedFormula")')Output (1st value is correctly evaluated, 2nd not):
"6", "1+2"

I can't directly pass @sParsedFormula to the query otherwise I get "The argument 1 of the XML data type method "query" must be a string literal". What is the correct XQuery-syntax to evaluate the SQL:variable?

View 2 Replies View Related

Need To Convert NULL Values To 0, (zero) In Order To Perform Math Calculations

Feb 20, 2007



Using a reporting services model/report builder we have two related tables:
- Fundings, (parent)
- Draws, (child)

Report Builder reports that subtract "Total Fundings.Amount", (which is SUM(FundingAmount)) from "Total Draw Amount", (which is SUM(DrawAmount)) to get a balance work as expected except when there are no Draw rows, in which case a NULL is returned. Obviously we want to convert NULL values of "Total Draw Amount" to zero so that when subtracted from "Total Fundings.Amount" the correct value is displayed. I've searched for a function similar to COALESCE (Transact-SQL) in report builder but found nothing.

Can anybody help me with this?



Thanks

Bruce

View 11 Replies View Related

Analysis :: Count Function Taking More Time To Get Count From Parent Child Dimension?

May 25, 2015

below data,

Countery
parentid
CustomerSkId
sales

A
29097
29097
10

A
29465
29465
30

A
30492
30492
40

[code]....
 
Output

Countery
parentCount

A
8

B
3

c
3

in my count function,my code look like,

 set buyerset as exists(dimcustomer.leval02.allmembers,custoertypeisRetailers,"Sales")
set saleset(buyerset)
set custdimensionfilter as {custdimensionmemb1,custdimensionmemb2,custdimensionmemb3,custdimensionmemb4}
set finalset as exists(salest,custdimensionfilter,"Sales")
Set ProdIP as dimproduct.dimproduct.prod1
set Othersset as (cyears,ProdIP)
(exists(([FINALSET],Othersset,dimension2.dimension2.item3),[DimCustomerBuyer].[ParentPostalCode].currentmember, "factsales")).count

it will take 12 to 15 min to execute.

View 3 Replies View Related

DB Design :: Create Two Column With Math Function In One Column?

Oct 5, 2015

How Can I Create Two Column with Math Function In one Column  Like Below. 

Create Table Tbl_V_Voucher_Details
(
Id Int IDentity (1,1) Primary Key, 
Catid Int Foreign Key References Tbl_V_Voucher_Info(Id),
ItemId Int Foreign Key References Tbl_V_Item(Id),
Discription varchar
(100),
Qty Int,
Price Float,
Qty * Price As Total 
)

View 5 Replies View Related

Count For Varchar Field - How To Get Distinct Count

Jul 3, 2013

I am trying to get count on a varchar field, but it is not giving me distinct count. How can I do that? This is what I have....

Select Distinct
sum(isnull(cast([Total Count] as float),0))

from T_Status_Report
where Type = 'LastMonth' and OrderVal = '1'

View 9 Replies View Related







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