Conditional Sum SQL - sql

I am very new to SQL and have been presented with, what seems to me, a complex task. I have a table which is generating the number of various fruit purchased on a given day. Thus:
G. A G.B
2016-06-01 Banana 45 0
2016-06-01 Pear 158 0
2016-06-01 apple 0 23
.... dates continue
I need to develop some kind of conditional sum to count how many types of fruit are bought with a specific grade on a specific date. So in the above case on the given date (2016-06-01) there would be 203 Grade A (G.A) bits of fruit and 23 Grade B (G.B) pieces of fruit.
Naturally some kind of
Sum(case when date=date then Grade else 0 ).
But, I am really baffled here. Please, any help would be greatly appreciated!!!!

A simple group clause should do the job here (Note: untested code)
select date, sum(grade_a) as grade_a_sum, sum(grade_b) as grade_b_sum
from sales
group by date;
This will give the grades for every date. Individual dates can then be selected if necessary.

Won't simple group by do the work..
Select
date,
sum(GA) as GA,
sum(GB) as GB
from
Table
group by date

Related

SQL How to get a count from the result of a formula in the same query

I have a query that provide the number of Year between 2 dates and call it Covg as a title in the query
select PLANS,DATEDIFF(YEAR, STARTDT, EXPDT) Covg
from PA
This is working and provide something like
Plans Covg
Payback 5
Standard 3
Payback 5
Payback 3
etc.
However, this is the result by customer. I need to know how many customers have a "covg" of 1y,2y,3y,4 years, etc. by plans
When I'm trying to add a Count for the Covg I get the message that Covg is not a column. This is true because it's a result of a formula
How can I do this?
The results should give me something like this example
(Yrs) #Of customers with the covg
PLANS Covg TL_Count
Payback 1 123
Payback 2 56
Standard 1 24
Standard 3 48
Standard 5 325
The last query I tried and get the error was
SELECT PLANS, DATEDIFF(year,STARTDT,EXPDT) COVG, COUNT(*)TL_Count
FROM PA
Group by PLANS, TL_Count
Try changing your GROUP BY to this:
SELECT PLANS, DATEDIFF(year,STARTDT,EXPDT) COVG, COUNT(*) TL_Count
FROM PA
GROUP BY PLANS, DATEDIFF(year,STARTDT,EXPDT)
You need your date function in the grouping, but not the COUNT() as it's an aggregation already.

SQL Flag consecutive (follow) records

I am relatively new to SQL and I tried to look for a similar question but I was not sure if the question related to my problem or that the answer might have been above skill level.
I think that the question is simple but I am not sure if the solution is simple.
I have the following sql table output
Room Name Time in Room Turnover Date
11 Mansson 740 NA 1/21/2017
11 Klein 841 NA 1/21/2017
11 Klein 1035 28 1/21/2017
I would like to write a query where I can flag fields where the following records are consecutive - Room, Name, Date.
This would flag the last 2 rows where Name is Klein.
Is there a way to do this, if yes can please guide me.
You can add a room/name/date flag using ANSI standard window functions:
select t.*,
(case when count(*) over (partition by room, name, date) > 1
then 1 else 0
end) as HasDuplicatesFlag
from t;

SQL Percentile function missing?

It is a mystery to me with this text book example. We have simply:
Transaction_ID (primary key), Client_ID, Transaction_Amount, Month
1 1 500 1
2 1 1000 1
3 1 10 2
4 2 11 2
5 3 300 2
6 3 10 2
... ... ... ...
I want to calculate in SQL the mean(Transaction_Amount), std(Transaction_Amount) and the some percentile(Transaction amount) grouped by Client_ID. But is seems, even given that percentile is a very similar calculation than the standard deviation, SQL cannot do it with a simple statement as:
SELECT
mean(Transaction_Amount),
std(Transaction_Amount),
percentile(Transaction_Amount)
FROM
myTable
GROUP BY
Client_ID, Month
Or can it?
It gets worse becuase I also need to Group By Month in addition to Client_ID.
Thanks a lot!
Sven
I'm sure Oracle can do the calculations you want. I just don't know what they are. You specify that you want something grouped by ClientId. Yet, your sample query has two keys in the GROUP BY.
Some functions that you want to look at are:
AVG()
STDDEV()
PERCENT_RANK()
Without sample data and desired results (or a very clear explanation of what you are trying to calculate), I can't put together a query.

How to count the number of active days in a dataset with SQL Server 2008

SQL Server 2008, rendered in html via aspx webpage.
What I want to achieve, is to get an average per day figure that makes allowance for missing days. To do this I need to count the number of active days in a table.
Example:
Date | Amount
---------------------
2014-08-16 | 234.56
2014-08-16 | 258.30
2014-08-18 | 25.84
2014-08-19 | 259.21
The sum of the lot (777.961) divided by the number of active days (3) would = 259.30
So it needs to go "count number of different dates in the returned range"
Is there a tidy way to do this?
If you just want that one row of output then this should work:
select sum(amount) / count(distinct date) as your_average
from your_table
Fiddle:
http://sqlfiddle.com/#!2/7ffd1/1/0
I don't know this will be help to you, how about using Group By, Avg, count function.
SELECT Date, AVG(Amount) AS 'AmountAverage', COUNT(*) AS 'NumberOfActiveDays'
FROM YourTable WITH(NOLOCK)
GROUP BY Date
About AVG function, see here: Link

SQL Get Weekly Count of product items

I am trying to get the total number entries into a table per week per product. Every time someone orders a product, it is entered into a database with the following information:
Table: Orders
order_id
order
order_date
There are 8 options for "order", which are pre-set and are never changing. I need to see the count per week of the items that are in that table..
I want to see something like this:
Order week 1 week 2 week 3 week 4 etc...
order1 30 10 11 23
order2 40 4 0 44
order3 88 23 12 22
Can someone tell me how that is achieved??
Thanks.. I'm so stuck on this.
as NickyvV indicated you want a pivot. However SQL Server cannot accept dynamic columns in a pivot, so you have to spell them out. Also you probably don't want the order_id in the first column, since you would only get 1s and 0s in the counts, but something like the product_id instead. So you could do something like this:
SELECT
product_id,
[week 1],[week 2],[week 3],[week 4],[week 5]
FROM
(SELECT
product_id,
'week ' + cast(DatePart(wk,[order_date]) as varchar(2)) as WeekName
FROM [Orders]) as o
pivot (count(WeekName)
for WeekName in ([week 1],[week 2],[week 3],[week 4],[week 5])) as p
Unfortunately, you'll have to spell out all possible week names. There would be ways using dynamic SQL, but i wouldn't recommend them as they are rather complex and nasty. Also, remember that if this is going into a report, you normally would do this pivoting in the reporting application (SSRS, etc.) instead of in the db.