I try to fix an SQL i did Earlier and have a problem while doing that.
I have an Huge SQL witch Calculate SUM Fields for a Report.
ATM The SQL Counts Every Vehicle, even when its a Electro Car.
CASE
WHEN AVG(mov.TOTALCONSUMPTION) >0
AND AVG((moving.TOTALTIME)) >0
THEN ROUND(AVG(mov.TOTALCONSUMPTION) / (AVG(mov.TOTALTIME)/3600), 4)
ELSE 0
END ConsumptionPerHour,
I need the Condition Where vehicle.energysource = 0 in my sql,
I try to build it in but allways get the err. "not a GROUP BY expression"
CASE
WHEN AVG(mov.TOTALCONSUMPTION) >0
AND AVG((moving.TOTALTIME)) >0
AND vehicle.ENERGYSOURCE= 0
THEN ROUND(AVG(mov.TOTALCONSUMPTION) / (AVG(mov.TOTALTIME)/3600), 4)
ELSE 0
END ConsumptionPerHour,
I know what the Error Mean but i have no Idear how to fix this.
Anyone have a Idear how i can solve this Problem?
(Btw its Oracle sql developer if that is helpfull)
Edit:
My Exact problem is that i cant put it in the Where part becouse my SQL have to Calculate some things with Electro Cars too like The driven Killometers Ect.
I have the Fuel Problem becouse i want to calculate the avg.
Lets say Car 1 is a Electro Car and Car to a Diesel Car.
The 1 one have a Consumption of 0(becouse Electric car) and the 2. one of 20.
My SQL now Calculate Sum of Consumption (Car 1+Car2 = 20) / amount of Cars:
Thats make a Avg Consumption of 10.
But i only need the Avg Consumption of all cars who are not electric cars.
Maybe a noob Question but im a Trainee and alone in the Office, so sorry if thats an Easy or bad explained question.
Okay i found a Solution, i simple created a Sub-Select and filter here if
vd.fuel = 0
Anyways, Thanks for Help.
Related
I am trying to calculate prevalence in sql.
kind of stuck in writing the code.
I want to make automative code.
I have check that I have 1453477 of sample size and number of people who has disease is 851451 using count.
The formula of calculating prevalence is no.of person who has disease/no.sample size.
select (COUNT(condition_id)/COUNT(person_id)) as prevalence
from disease
where condition_id=12345;
when I run above code, I get 1 as a output where I am suppose to get 0.5858.
Can some one please help me out?
Thanks!
In your current query you count the number of rows in the disease table, once using the column condition_id, once using the column person_id. But the number of rows is the same - this is why you get 1 as a result.
I think you need to find the number of different values for these columns. This can be done using count distinct:
select (COUNT(DISTINCT condition_id)/COUNT(DISTINCT person_id)) as prevalence
from disease
where condition_id=12345;
You can cast by
count(...)/count(...)::numeric(6,4) or
count(...)/count(...)::decimal
as two options.
Important point is apply cast to denominator or numerator part(in this case denominator), Do not apply to division as
(count(...)/count(...))::numeric(6,4) which again results an integer.
I am pretty sure that the logic that you want is something like this:
select avg( (condition_id = 12345)::int )
from disease;
Your version doesn't have the sample size, because you are filtering out people without the condition.
If you have duplicate people in the data, then this is a little more complicated. One method is:
select (count(distinct person_id) filter (where condition_id = 12345)::numeric /
count(distinct person_id
)
from disease;
The picture below shows a table of accounts and the outcomes that I want to count. Ie every time the account number is 106844 and the outcome is "MESSAGE" or "ESCALATION EMAIL" that should count as 1 where any other outcome counts as 0. What I would normally do is a horrible mess of iifs like
sum( iif([account] = '106719' and [Outcome] in ('MESSAGE','ESCALATION_EMAIL'),1,iif([account] = '310827' and [outcome] <> 'ABORT' and 'CALL_OUTCOME_LB' in ("Call patched to Customer Care","Message Taken"),1,iif( ... , 0) as [Total Outcomes]
and so on but man it feel like there's got to be an easier way or one less prone to making a random mistake in the 7th nested iif and messing the whole thing up. Any ideas?
Don't use iif(). It is a function brought into SQL Server for back-compatibility to MS ACCESS. Why would you want to be backwards compatible to such a thing?
Use the ANSI standard CASE expression:
sum(case when account = '106719' and Outcome in ('MESSAGE', 'ESCALATION_EMAIL')
then 1
when account = '310827' and outcome <> 'ABORT' and
'CALL_OUTCOME_LB' in ("Call patched to Customer Care", "Message Taken")
then 1
. . .
else 0
end) as Total_Outcomes
I would also advise you to name your columns so they don't need to be escaped (why "Total Outcomes" became "Total_Outcomes"). That simplifies the code.
Why not use a lookup table that has the Account and Outcome and use that? Then, as requirements change, you could update the lookup table and not worry about your code.
Yeah... there is
The last parameter is for when the condition is false, everything else will fall in there.
SUM( IIF([ACCOUNT] = '106719' AND [OUTCOME] IN ('MESSAGE','ESCALATION_EMAIL'),1,0))
I have a table which display various data and what I want is it to calculate a percentage in which the total has increased by, so for example:
Total is £1000
TotalAfterMarkup is £1500
=SUM(Fields!Total.Value -
Fields!TotalAfterMarkup.Value) /
(Fields!TotalAfterMarkup.Value)
the above code calculates the Percentage to -50% which is incorrect but ill be able to work that out. What i want is to now put this statement into an SUM IF statement. currently i get the #Error if the TotalAfterMarkup < 1 so i need something like
IF TotalAfterMarkup.Value >0 THEN
=SUM(Fields!Total.Value -
Fields!TotalAfterMarkup.Value) /
(Fields!TotalAfterMarkup.Value)
ELSE 0.00%
is this possible, thanks for any help guys
Unfortunately I don't have enough rep to comment, otherwise I wouldn't post this as an answer. Really, I need a little more information. Are you doing this as an expression within the report builder or as part of your dataset?
If its part of your dataset then I suggest using a case statement.
case
when TotalAfterMarkup.Value >0
then SUM(Fields!Total.Value -
Fields!TotalAfterMarkup.Value) /
(Fields!TotalAfterMarkup.Value)
else '0.00%'
end [MyFieldName]
Using an IIF Statement: ("Dataset = Your Dataset Name")
=IIF(Fields!TotalAfterMarkup.Value, "CostTable") >0, SUM(Fields!TotalCost.Value, "CostTable") - (Fields!TotalAfterMarkup.Value, "CostTable") / (Fields!TotalAfterMarkup.Value, "CostTable"), "0.00%")
I think this should work:
=IIF(TotalAfterMarkup.Value > 0,(SUM(Fields!Total.Value -
Fields!TotalAfterMarkup.Value)/(Fields!TotalAfterMarkup.Value)),0)
The IIF function is the one you use for evaluating conditions in SSRS:
Expression Examples (Report Builder and SSRS) - See decision function section
As part of my course in university I have to make a database in Microsoft Access which is somewhat limiting me on what I'm trying to do. I have a table that has the information of whether a player in a team was present for a fixture or not using the values "P", "R", and "M" (Played, Reserves, Missed). I want to make a query that counts a value of 1 for each value of P or R and a separate one for M, so that when I make a report that prints off a membership card, it shows the amount of fixtures they've played in and the amount of fixtures that they have missed.
Sorry if this isn't clear, I'll try to explain myself further if you ask but I'm not very good with this stuff. Thank you.
Edit: I'll use screenshot links if that's okay, here is the Fixture Attendance entity that shows if a member of a team attended a game or not. I'm making a membership card based off this one. I want to be able to display the No. of fixtures played by the member and the No. of fixtures missed based off the values in the above entity and use that information in a form I'm going to create. That will be a subform inside my Membership Card form.
I'm presumably really bad at explaining this - I understand Access is rarely used in the real world so I'm not sure why I'm doing this in the first place and don't feel like I'm getting any real knowledge of working with databases.
You should use the COUNT function.
http://office.microsoft.com/en-us/access-help/count-data-by-using-a-query-HA010096311.aspx
I am guessing that you want something like this:
select playerid, sum(iif(fixture in ("P", "R"), 1, 0)) as NumPR,
sum(iif(figure = "M", 1, 0)as NumM
from table t
group by playerid;
The key idea here is putting the conditional part (iif()) inside the sum().
CASE WHEN can be used to translate the codes into 1's and 0's. Then use SUM with a GROUP BY to sum them.
SELECT player_id, SUM(Played), SUM(Reserve), SUM(Missed)
FROM
(SELECT player_id,
CASE WHEN present = 'P' THEN 1 ELSE 0 AS Played,
CASE WHEN present = 'R' THEN 1 ELSE 0 AS Reserve,
CASE WHEN present = 'M' THEN 1 ELSE 0 AS Missed
FROM fixtures)
GROUP BY player_id;
I stumbled across this website and instantly fell in love. Let me be completely honest, I have little to NO knowledge of Access.. I told my manager this and he still insists that I "can figure it out" which is highly doubted. So here I am asking for help.. On to the question:
Where are the SQL code gurus? haha
I have 2 tables, "Found" & "Missing", both showing inventory adjustments for our building within the company. (Amazon)
I believe I have the process figured out but have no idea how it looks within Access..
Step 1: Group by ASIN (basically the numerical version of a barcode)
Step 2: Determine the +/- for the grouped ASINs in both lists
Step 3: Use TOP function to find the largest negative adjustments
There is a total of 3000+ records in both spreadsheets, but hopefully if I can figure out the process then the input/output wouldn't matter.
I thought maybe I needed a unique identifier? Bin(location) + ASIN(barcode) + Quantity
As you can see.. I have been thinking, organizing, and praying someone can help!
Here is a dummy example of the "Found" spreadsheet, the "Missing" spreadsheet is the exact same format with the only difference being a "M" instead of a "F" under "Reason Code"
Hopefully this is enough information, I know its a cluster.... thanks guys!
Date FC Application Name IOG ID IOG Name Container Id GL Product Group ASIN Processed By Reason Code Quantity Item Cost
1/5/2014 RIC1 FCICQACountService 1234 Doll Inc. P-1-A101xxx Toy B000000001 unknown1 F -1 12.34
1/5/2014 RIC1 FCICQACountService 1334 Amazon P-1-A101xxx Drugstore B000000002 unknown2 F -1 10.36
1/5/2014 RIC1 FCICQACountService 1432 Amazon P-1-A102xxx Office Product B000000003 unknown3 F -13 50.50
1/5/2014 RIC1 FCICQACountService 1442 Amazon P-1-A102xxx Office Product B000000004 unknown4 F -2 223.62
1/5/2014 RIC1 FCICQACountService 1337 Hope Inc. P-1-A102xxx Office Product B000000005 unknown5 F -1 100.99
I take it that by "spreadsheet", you actually mean "table". Might be a good idea to find a good primer on SQL and relational databases in general.
You've got a pretty good start, though. You've identified what you want. Note that in SQL, this is what you usually do; you think more about the result you want than you do the process of getting it. Each of your points suggests a keyword or function that will go into your query:
1) "Group by ASIN (basically the numerical version of a barcode)": You probably want to use the GROUP BY keyword.
2) "Determine the +/- for the grouped ASINs in both lists": Sounds like you want to SUM up a column here.
3) "Use TOP function to find the largest negative adjustments": Obviously, you already know you want TOP. The piece you're missing, though, is that the "largest negative" part suggests you want to use ORDER BY, and you want the smallest (largest magnitude negative) first. That will make sure that the right row is on top when it takes the top one.
So putting all that together, the only thing you need to figure out is the syntax. Your end query probably looks something like this:
SELECT TOP 1 ASIN, SUM(Quantity) AS TotalQuantity FROM Found GROUP BY ASIN ORDER BY SUM(Quantity);
This will calculate the sum of Quantity for each group of rows that has the same ASIN, and the result will be a set of rows that contain the ASIN and the total Quantity for that ASIN. Then it sorts the rows using the total quantity, with the smallest (most negative) row on top. The TOP then cuts off all the other rows. You could optionally leave out the TOP 1 if you want to see all the rows.
By the way, this SUM function is a little special. It's what we call an aggregate function. That's because it does something with a bunch of values across many rows. Not all functions are like that in SQL, but this one is.
If this isn't exactly what you're looking for, I hope it's enough to get you off the ground. Good luck.