How Do I Calculate Percentages? It's Supposed To Be EASY!

Jun 29, 2004

here's my code...





DECLARE @Output FLOAT


SELECT @Output=(@Part/@Whole)*100





When I substitute my parameters like this:





SELECT @Output=(5/20)*100





The answer is always 0.0!


But if I do this:





SELECT @Output=(5*100)/20





I get the correct answer.


Why is this so?


What is the correct way in SQL to calculate percentage??!!!

View 3 Replies


ADVERTISEMENT

Using OVER Clause To Calculate Percentages

Jun 25, 2015

I've always user over with partitioning however recently I am looking at some other code and they have calculating percentages using over. I'm at a lost on why you would do this.

Example would be

CAST(TABLE1.UNIT AS DECIMAL (6,2)) / SUM(TABLE2.UNIT) OVER () AS UNIT_%

What about be the advantage of using OVER there?

View 3 Replies View Related

Code To Calculate Percentages By Month?

Mar 30, 2015

I have a query which provides the total number of each of 2 invoice flags per month, starting 1st Feb this year. I also need a percentage calculated for each of the 2 flags by month. However, it is showing the totals correctly for each of the flags by month, but the percentage is using the total of both flags for all months, and so it is wrong if I only want to look at one month. The query is as follows along with a sample output including % which are incorrect.

How can I correct this so that it shows the right % for each of the flags for each month?

Select
sk.Period Period,
sk.[Invoice Flag],
count(*) * 100.0 / Sum(count(*)) Over () Percentage,
count(*) Total1
From
(Select wh.worknumber [Work Order],

[code].....

Output at present:

Period Invoice Flag Percentage Total1
--------------------------------- ------------------------------- --------------------------------------- -----------
2015-02 Invoiced after 7 days 5.704697986577 136
2015-03 Invoiced after 7 days 2.097315436241 50
2015-02 Invoiced with Customer Approval 59.563758389261 1420
2015-03 Invoiced with Customer Approval 32.634228187919 778

View 2 Replies View Related

Group Expression That Calculate Percentages.

Mar 8, 2007

I have an expression in a group that calculates percent of sales:

=iif(Sum(Fields!BOOKD.Value)=0,0,IIF(Sum(Fields!NET.Value)=0,0,((Sum(Fields!BOOKD.Value)-Sum(Fields!NET.Value))/Sum(Fields!BOOKD.Value))))*100

The problem I'm having is that if both the

Sum(Fields!BOOKD.Value)=0 and

Sum(Fields!NET.Value)=0 ,

the expression returns the message #ERROR instead of a 0.



I have the initial query set to display 0 if the value is null.

,SUM(ISNULL(R.BOOKD,0))BOOKD
,SUM(ISNULL(R.NET,0))NET



I would greatly appreciate any help on how to solve this issue.

Thank Barb

View 4 Replies View Related

Reporting Services 2005 - Matrix Grouped Report - Calculate Percentages

Jun 29, 2007

Hi,



Could someone help with the following problem, I what to create a cross-tab report of the following data, grouped by Colour:

RAW DATA








Name
Colour

Sarah
Black

Kim
Red

Jane
Black

Jane
Pink

Robert
Yellow

Tom
Green

Tom
Black

Billy
Black

Sarah
Black

Sarah
Black

Tom
Pink

Kim
Pink

Robert
Black



Group Colours by Names Report










Number





Proportions %





Name
Black
Green
Pink
Red
Yellow
Total by Name
Black
Green
Pink
Red
Yellow

Billy
1




1
100.00%
0.00%
0.00%
0.00%
0.00%

Jane
1

1


2
50.00%
0.00%
50.00%
0.00%
0.00%

Kim


1
1

2
0.00%
0.00%
50.00%
50.00%
0.00%

Robert
1



1
2
50.00%
0.00%
0.00%
0.00%
50.00%

Sarah
3




3
100.00%
0.00%
0.00%
0.00%
0.00%

Tom
1
1
1


3
33.33%
33.33%
33.33%
0.00%
0.00%





I want to produce a Matrix cross-tab report, like the above, within Reporting Services. Any suggestions welcome



Many Thanks,



Radha

View 5 Replies View Related

Package Does Not Stop When Supposed To

Nov 19, 2007

Hi,

I have a package with For Loop container.

It looks like this:

FOR LOOP (until @IsCurrent < 1) [
[Execute Package Task 1] --> [Execute Package Task 2] --> [Execute SQL Task] --expression--> [Script Task]
]

So, in the [Execute SQL Task], it runs a stored procedure, which returns a 0 or 1 value, which is bound to the variable @IsCurrent. The variable then gets evaluated in the "expression." If @IsCurrent is 0, execution continues to the [Script Task]. That part works fine.

The problem is occurring in the [Script Task] portion. All the Script Task does is "sleep" for 3 minutes. Here is an excerpt of the code:


Dts.Variables("sleepCounter").Value = CInt(Dts.Variables("sleepCounter").Value) + 1

If CInt(Dts.Variables("sleepCounter").Value) = 20 Then

Dts.TaskResult = Dts.Results.Failure

Exit Sub

End If

So, as you can see, if "sleepCounter" = 20, it fails the task, which should then fail the package, right??

However, the package keeps running, even after sleepCounter has exceeded 20. The MaximumErrorCount on the For Loop container is set to 20 also. So after 20 failures, this package should fail, but it isn't!

Any ideas?

Thanks

View 9 Replies View Related

ForceExecutionResult Doesn't Do What Its Supposed To.

Jul 17, 2007

[Microsoft follow-up]



All,

According to BOL the ForceExecutionResult property can be used to imitate real-time failure (http://msdn2.microsoft.com/en-us/library/microsoft.sqlserver.dts.runtime.dtsforcedexecresult.aspx).



However, I've just done a very simple test and this appears to not be the case. Here's the repro:



Start a new package
Drag on a Sequence Container
Set the sequence container property ForceExecutionResult='Failure'

When you run the package the sequence container will complete successfully. As far as I can see its not supposed to.



Any comments?



Thanks

Jamie

View 10 Replies View Related

SSIS Error Output -- How Is It Supposed To Work?

May 29, 2006

I€™m importing a Flat file (delimited text) into a sql server database table and trying to trap any import errors in another output Flat file.

I create a Flat File Source task. After tweaking the task, the Source €œError Output€? tab shows all the input columns and all €œError€? and €œTruncation€? values are set to €œRedirect row€?

Next I add a €œSQL Server Destination€? task and connect the Source green arrow to it.

Finally I add a Flat File Destination task (error Output task), connect the Source red arrow to it, click €œOK€? in the €œConfigure Error Output€?, and finally add a connection manager to the Error output task. When I look at the Mappings tab of the Error Output file it shows only three available input columns: €œFlat File Error Output Column€?, ErrorCode, and ErrorColumn

I€™m not sure where they came from but that info is not very useful to me. I want to know which line the error occurred on as well as the bad column(s). If nothing else, I need to see at least the actual row that was bad. How can I get that information?



Barkingdog

View 8 Replies View Related

Using Percentages

May 1, 2008

The formula for percentage safe = sum(safe)/ sum(safe)+sum(unsafe)*100.0

This works well on a calculator. Could someone show me how to achieve this in sql please. If we use safe = 92 and unsafe = 117

This forum is great!

Regards Phill

View 5 Replies View Related

Calculating Percentages For Each Row

Dec 10, 2007

One more for you while I'm trying to remember my SQL skill from a few years ago (last one of the day - promise):
My database looks like:

(Ignore that the ERD is in Access, the database is SQL Server 2005)

How do I calculate sales percentages?
I.E. how do I calculate the percentage that each product has sold as a percentage of the total sales?

What I'm aiming for is each row of products is shown, with its percentage of the whole sales.

AVG is involved this time, isn't it?

The productID is of the int datatype (not that you need to know that field - but never mind) and the quantity is a smallint, before you ask


Thank you in advance for any replies.


Paul

View 5 Replies View Related

Comparing Percentages

Mar 17, 2008

hi

i have a three fields in my table..those are


FromPercentage -Varchar(30)
ToPercentage -Varchar(30)
Scale -Int(11)

i have the percenatge that 10%...now i want to check that whether this 10 % is in between the frompercentage and topercentage..if it is there i want to return the the scale value..how can i do this in sql.

i know comparing when it is integer using where and and operator..but i dont know how use if it has the percentages.


Ram

View 1 Replies View Related

Stuck On Percentages...

Apr 18, 2008

most my fields that I am interested in getting percentage values for have to be counted first.... I am having problems converting the counted values to percentages. I don't think I am doing it right...

I would greatly appreciate an example of a very simple matrix table with a counted value that displays percentages. I have found examples online but are part of a much more complex table and I can't seem to get thier formating to work on mine.

Kind regards,

Rich

View 6 Replies View Related

Calculation For Totals Using Percentages

Jan 25, 2006

I am trying to figure how write sql statement that will give the total cost.

unit price * quantity - discount = total cost

Unit price = 9.8
quantity = 30
discount = 0.15

View 2 Replies View Related

Return Percentages In The Query.

Oct 13, 2006

Hello,I'm trying to something that just works in Oracle, but does not in SqlServer.How can I get the percentage of two counts to be returned on each rowof the query?select count(sid), /* all not the not null */count(*),(count(sid) /count(*) ) as percent_not_null,4 as four,(3/4) as three_over_fourfrom dbo.sysusers7082040Incredibly, it changes even 3/4 into a zero!For efficiency, I want the percentage returned in the query.And to not use variables and coding. Efficiency,both of the server, and of my time.Note: I am using dbo.sysusers as an EXAMPLE only. My realquery will be on user defined application tables.What is the solution please?

View 4 Replies View Related

Expressing Values As Percentages

Jul 20, 2005

I have two values and I want to express a third derived value as apercentage of the other two values. I thought it would be a simpledivision of the first two numbers and then a multiplication by 100 togive me a percentage, but all I get is 0.Here is my select statement,SELECT dbo.Eligble.GRADETotal,dbo.nil1234_Faculties_Totals.FACTotal,dbo.nil1234_Faculties_Totals.FACTotal /dbo.Eligble.GRADETotal * 100 AS [PERCENT]FROM dbo.Eligble CROSS JOINdbo.nil1234_Faculties_TotalsCan anyone point out where I'm going wrong here?Thanks in advance

View 2 Replies View Related

Creating Dataset For Report - Percentages In Result

Nov 3, 2015

Trying to create a dataset for a report. I need to bring back percentage in the result set. The fields that I am using to get the percentage have valid data but the result field is 0.00%. Is there reason I cant bring back a percentage field?

Code:
SELECT JobNum, Mailed, LT_7, BT_6_10, GT_10,
Format([LT_7]/[Mailed], 'p') AS PctScaned1,
Format([BT_6_10]/[Mailed], 'p') AS PctScaned2,
Format([GT_10]/[Mailed], 'p') AS PctScaned3,

[Code] ....

View 3 Replies View Related

Calculating Percentages And Showing In Separate Columns

Aug 31, 2013

SELECT DISTINCT CASE WHEN SM.SERVICE_TYPE_N = 1 THEN 'LABORATORY'
WHEN SM.SERVICE_TYPE_N = 2 THEN 'PODIATRY'
WHEN SM.SERVICE_TYPE_N = 3 THEN 'ADMINISTRATION'
WHEN SM.SERVICE_TYPE_N = 4 THEN 'DIET'
WHEN SM.SERVICE_TYPE_N = 5 THEN 'DENTAL'

[Code] ....

In the above query i need to calculate 100%,30% and percentage other than 100 and 30 and show them in separate columns how to do that?

1)ROUND(SUM(BM.CONCESSION_AMOUNT_M),2)AS [100_PERCENT]
WHERE BM.BILL_AMOUNT_M=BM.CONCESSION_AMOUNT_M

2)ROUND(SUM(BM.CONCESSION_AMOUNT_M),2)AS [30_PERCENT]
WHERE AND BM.CONCESSION_AMOUNT_M=BM.BILL_AMOUNT_M * 0.30

3) ROUND(SUM(BM.CONCESSION_AMOUNT_M),2)AS [OTHER_CONCESSION_PERCENT]
WHERE BM.CONCESSION_AMOUNT_M between BM.BILL_AMOUNT_M*0.001 and BM.BILL_AMOUNT_M*0.299
OR BM.CONCESSION_AMOUNT_M between BM.BILL_AMOUNT_M*0.301 and BM.BILL_AMOUNT_M*0.999

View 3 Replies View Related

Calculating Percentages Based On Multiple Rows

Oct 2, 2014

I have two tables that look like this (below). One tells me the name of my product, the Amazon Category it is in & the amount that I want to sell it for. The other tells me the Category & the fee for that category. So far so good. Though it gets tricky in the sense that some categories have two tiers. So in Electronics, the fee for $0.00 - $100.00 is 15%. But from $100 and up it is 8%.

Since it has two columns & both of the new columns pertain to the fee of my product, I can't figure out how to use both at once. For my $599.99 example it would be ($100 * 0.15) + ($499.99 * 0.08) = $55.00. Would I pivot the data? If not, how would I group it to be considered together?

Category Example

IDAmazonCategoryIDAmazonCategoryNameFeePercentageStartPriceEndPrice

1apsAllDepartments0.150.000.00
2instant-videoAmazonInstantVideo0.000.000.00
3appliancesAppliances0.150.000.00

Product Example

1Product1Electronics9.99
2Product3Electronics99.99
3Product2Electronics599.99

Raw SQL
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE #Amzn_Category_FeeStructure(
[ID] [int] IDENTITY(1,1) NOT NULL,

[Code] ....

I use Microsoft SQL 2008

View 2 Replies View Related

Label Stacked Bar/column Chart With Percentages

Mar 11, 2008

Hi,

I need to label stacked bar /column charts with the percentage of each series at each axis point.

For example, if I have the following values in the chart:

Series 1 Series 2
Axis point 1 50 25

Axis point 2 12 12



I need the labels to read: Series 1 Series 2
Axis point 1 67% 33%

Axis point 2 50% 50%


It would seem that I need to format the data point labels to read something like: sum (data.label)/sum(data.label, "axis point")

Any ideas would be appreciated. Thanks in advance for your elegant solutions

View 3 Replies View Related

Funky Formatting Of Percentages In Excel Export

Sep 18, 2007



I've created a report that has cells in it that I want to be formatted as percentages. I set the format code in the cell properties to "P1" and everything appears to work fine until I export to Excel. Some cells show up with only one digit after the decimal and some show up with two digits after the decimal.
I looked at the formatting in Excel (right click, Format Cells...) and it is set to "[$-1010409]#,##0.0#%". I don't have the first clue what that is "supposed" to do but what it does is this:

If I enter 100.00 in the cell it shows up as 100.0%. Expected
If I enter 100.10 in the cell it shows up as 100.1%. Expected
If I enter 100.15 in the cell it is displayed as 100.15%. Not expected

I have formatted the report to only show one digit after the decimal, but RS exports to Excel with some funky formatting that sometimes shows one digit and sometimes two digits after the decimal. Why wouldn't it simply format the cell as a percent? How can I get it to only show a single digit after the decimal?

This is Excel 2007 but Excel 2003 has the same behavior.

Thanks
--John

View 5 Replies View Related

I Know This Is Easy But...

Jun 9, 2004

I'm banging my head against the wall. It's probably pretty simple so here goes...

I have a form that supposed to add records to a table on the database. I'm pretty sure I have the dataAdapter and Dataset set right but when I add a record, it complains that the primary key can’t be null. I’ve tried different things, including removing those fields and variables from the stored Proc, changing the Identity Properties of the Table, changing the AutoIncrement settings on the Dataset for that field, but all give me different errors. Nothing actually makes it work. This database has many records in it and the Primary key is a decimal field that starts at 5, then next was 10, then 28, then it started getting consecutive after 110. (111, 112, 113, etc.) (I'm porting over an old database to a new web site, so I'm somewhat contrained by the database.)

I guess my question is for adding records in to a database that has a primary unique key constraint. Certainly this is a pretty common thing. Obviously I do not want users to enter that in themselves, I thought it should simply autocreate/autonumber. So what is the best procedure and gotcha’s I need to watch out for?

View 7 Replies View Related

C# Sql Easy Help

Sep 16, 2004

if i have the following code, how do i know if the transaction was actually successful, so basically where in this code can i write TRANSACTION SUCCESFUL?

try
{
//Open up the connection
conn.Open();
//Setup the Transaction
trans = conn.BeginTransaction();

//First query in transaction
pre_query = "Delete from Menu where spec_name="
+ "'"
+ spec_name_array[i].Text.ToString()
+ "'" ;

//Second query in transaction
query = "INSERT into Menu VALUES ('"
+ Calendar1.SelectedDate
+"','"
+ spec_name_array[i].Text.ToString()
+"','"
+ spec_desc_array[i].Text.ToString()
+"','"
+spec_price_array[i].Text.ToString()
+"',1)";
SqlCommand comm = new SqlCommand(pre_query,conn);
//Setup the command to handle transaction
comm.Transaction = trans;
//Execute first query
comm.ExecuteNonQuery();
//Add in second query
comm.CommandText = query;
//Execute second query
comm.ExecuteNonQuery();
trans.Commit();
}
catch(SqlException ex)
{
com_label.Text = "Submission Not complete, did you forget the date or something else?";
//Undo all queries
trans.Rollback();
}
finally
{
conn.Close();
}

View 1 Replies View Related

Should Be Easy...Someone Has To Have Done This Already

Aug 16, 2006

This may not be the right place for this post...but my head is hurting and I can't think right now.

I have a SQL table of users. Each record has a required 'Birthdate' field. I'd like to order this by the days left till the give birthday, keeping in mind that the year may be 1980 or their birthday might have been 2 weeks ago.

Can someone cure my headache?

View 1 Replies View Related

This Should Be Easy But It's Not.

Mar 3, 2006

I have written 2 custom connection mgr€™s.
One connects the data from an oracle source
One connects so I can put the data on a sql server.
These both work well and it makes it a lot easier across development, test, production.

But now I would like a good way to do this

I have 10 tables to copy from oracle. The only difference is just the name of the table.

static string[] g_tables =
{
"table_name_1",
"table_name_2",
"table_name_3",
€¦
};

foreach (string str_table in g_tables)
{
Oracle.DataAccess.Client.OracleCommand OracleCommand = new Oracle.DataAccess.Client.OracleCommand
(
"select * from " + str_table,
OracleConnection
);
Oracle.DataAccess.Client.OracleDataReader OracleDataReader =
OracleCommand.ExecuteReader();

// dump out to raw file destination

}

I understand there are some pieces left out but that is the basic idea. It seems like I€™m going to have write custom pieces for each step.

It does not seem like there is any advantage to using SSIS. Should I give up now and stick to writing windows services for stuff like this?

I could just write a specific piece for each table but the only difference is the table name.

View 13 Replies View Related

Hopefully An Easy One

Sep 5, 2006



I need to determine the top 20 most frequent occurences of a value in a specific field using SQL.

View 4 Replies View Related

What Is The Easy Way To Do This?.

Oct 30, 2007

My table structure...
enddt datetime(8)
status varchar(20)

when enddt time equal to server time.

I want to change status field to expired.

What is the easy way to do this?.


enddt status
8/22/2005 7:00:00 PM expired
9/22/2005 8:30:00 PM expired
10/30/2005 7:30:00 PM live
11/22/2005 9:30:00 PM live

View 6 Replies View Related

Easy ....If Else

Sep 18, 2007



I completely forgot how to do this. I want one of my groups in the matrix to take its week number (1-7) as Monday-Sunday.


so it would kind of be like this:


=IIF(Fields!DayOfWeek.Value=2,"Mon",

ELSE(Fields!DayOfWeek.Value=3,"Tues",

Else(Fields!DayOfWeek.Value=4,"Wed",

etc etc

Am i doing this right, or am i off??

View 4 Replies View Related

I Think This Is An Easy One...

Sep 5, 2007

If I have a 64 bit version of SQL 2005 installed, will "select @@version" indicate it is a 64 bit version? If not, how do I determine such? Thanks in advance.

View 3 Replies View Related

Has To Be Easy!

Oct 4, 2007



I have a column in my report that i want to show percentage change from the previous year to this year. So i enter all kinds of different type of formats for the formula, and keep getting the wrong answers or error messeges. Here's what i have tried recently:


=SUM((Fields!LYTD_Amount.Value - Fields!YTD_Amount.Value) (Fields!YTD_Amount.Value*100))

Its pretty much Last year to date Minues Year to Date , Divided by Year to Date, Multiplied by 100.

any suggestions? Everytime i try to put an aggregate in the box, its always tricky.

View 13 Replies View Related

SQL Query (ought To Be Easy)

Dec 21, 2006

hi,
I have this simple sql query - it should be pretty obvious what I'm trying to achieve but this syntax isn't accepted on SQL 2005, any suggestions?
 SELECT Name FROM Users WHERE UsersID IN (EXEC dbo.ReturnDataByModule 'Groups',1200)

View 6 Replies View Related

Easy Question

Oct 19, 2007

What is the equivalent of Double for SQL Server? 

View 1 Replies View Related

An Easy One: The Need For Relationships?

Mar 16, 2008

 Ok - I am still a bit weak on SQL.  My understanding of FK relationships in a database are to reinforce the data integrity - Correct?  For example, does it make sure that the id given for SiteID does indeed exists.  Can it link tables like JOIN in select statements? If not, is there any gains by creating them, such as performance?

View 1 Replies View Related

Another Easy One: Views

Mar 16, 2008

 scenario I have 2 tables one is called "Site" which contains columns ID, Address1, Address2,City,StateID,ZipCode and the second table is called "State" which contains columns ID,Name,Abbreviation.  I am looking to make a view that contains all the sites with the state inner joined on stateid to make my all my other queries easier. That is so I can just select from the view without having to do the inner join on the state.  My question is when a new record is added to table Site do I have "recreate"/update the view?

View 3 Replies View Related







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