Decrease Date for Average on this SQL - sql

I want to query price average from my top 25 price sort by last date (and select some symbols).
I use this code, It's Work !!
SELECT AVG(PRICE)
FROM (SELECT PRICE FROM ms_data where SYMBOL='$symbol'
ORDER BY DATE DESC LIMIT 25) var;
If I don't want top date or 2 top date.
Example.
top date (lastest date) = 2014-04-16
2nd of top date = 2014-04-15
3rd of top date = 2014-04-4
...
I should not query first result,right?
I use this code but It doesn't work.
SELECT AVG(PRICE)
FROM (SELECT PRICE FROM ms_data where SYMBOL='$symbol' AND
NOT EXISTS (SELECT PRICE FROM ms_data where SYMBOL='$symbol'
ORDER BY DATE DESC LIMIT 1) ORDER BY DATE DESC LIMIT 26) var;
If use variable instead of limit.
SELECT AVG(PRICE)
FROM (SELECT PRICE FROM ms_data where SYMBOL='$symbol' AND
NOT EXISTS (SELECT PRICE FROM ms_data where SYMBOL='$symbol'
ORDER BY DATE DESC LIMIT $i) ORDER BY DATE DESC LIMIT 25+$i) var;
Any suggestion?
Thank you in advance.

Related

SQL to find when amount reached a certain value for the first time

I have a table that has 3 columns: user_id, date, amount. I need to find out on which date the amount reached 1 Million for the first time. The amount can go up or down on any given day.
I tried using partition by user_id order by date desc but I can't figure out how to find the exact date on which it reached 1 Million for the first time. I am exploring lead, lag functions. Any pointers would be appreciated.
You may use conditional aggregation as the following:
select user_id,
min(case when amount >= 1000000 then date end) as expected_date
from table_name
group by user_id
And if you want to check where the amount reaches exactly 1M, use case when amount = 1000000 ...
If you meant that the amount is a cumulative amount over the increasing of date, then query will be:
select user_id,
min(case when cumulative_amount >= 1000000 then date end) as expected_date
from
(
select *,
sum(amount) over (partition by user_id order by date) cumulative_amount
from table_name
) T
group by user_id;
Try this:
select date,
sum(amount) as totalamount
from tablename
group by date
having totalamount>=1000000
order by date asc
limit 1
This would summarize the amount for each day and return 1 record where it reached 1M for the first time.
Sample result on SQL Fiddle.
And if you want it to be grouped for both date and user_id, add user_id in select and group by clauses.
select user_id, date,
sum(amount) as totalamount
from tablename
group by user_id,date
having totalamount>=1000000
order by date asc
limit 1
Example here.

How do I get all rows from the second to latest date?

I have gotten all rows for the latest date like this:
SELECT date, quarter, sales_region, revenue
FROM regions
WHERE date = (SELECT MAX(date) FROM regions)
ORDER BY 1
So how would I get the rows for the second latest date?
I have tried but no luck:
SELECT MAX(date), quarter, sales_region, revenue
FROM regions
WHERE date < (SELECT MAX(date) FROM regions)
ORDER BY 1
Here is one method:
SELECT date, quarter, sales_region, revenue
FROM regions
WHERE date = (SELECT DISTINCT date
FROM regions r2
ORDER BY date DESC
OFFSET 1 FETCH FIRST 1 ROW ONLY
)
ORDER BY 1;
Another method uses dense_rank():
select r.*
from (select r.*, dense_rank() over (order by date desc) as seqnum
from regions r
) r
where seqnum = 2;
Gordon answered your question precisely, but if you want to get the records for the last two dates in one query, you could use IN instead of =, and get the top two records with LIMIT 2:
SELECT date, quarter, sales_region, revenue
FROM regions
WHERE date IN (SELECT DISTINCT date
FROM regions r2
ORDER BY date DESC
LIMIT 2)
ORDER BY 1;
Starting with version 8.4, you can also use FETCH FIRST 2 ROW ONLY instead of LIMIT 2.

select highest sale with date from sql table

select max(total), date
from (select sum(total) as total, date as date
from canteen
group by date) as max
i want to select the highest sale and the date of the highest sale from table.
With my query this error is shown.
Exception, Error code 8,120, SQLState S0001] Column 'max.date' is
invalid in the select list because it is not contained in either an
aggregate function or the GROUP BY clause.
You can use order by, set your data to order by sale descending and fetch first row.
If you wants result by date then you can use ROW_NUMBER()
select TOP(1) total, date
from
(
select sum(total) as total, date as date
from canteen
group by date
) as max
Order by todal desc
This will return all dates achieving the max sales total. Here is a demo.
; with x as (
select sum(total) as total, date from canteen group by date
)
, y as (
select dr = dense_rank() over(order by total desc), *
from x
)
select * from y where dr = 1
If you want to get all dates with max(total), here it is
;with temp as
(
select sum(total) as total, date as date
from canteen
group by date
)
SELECT TOP 1 WITH TIES *
FROM temp
ORDER BY temp.total desc
You have forgotten to add group by & order by in your outer query. I have modified it to display all the sales in descending order. So the highest sale will be at top.
select max(total) total, date
from (select sum(total) as total, date as date
from canteen
group by date) as max
group by date
order by total desc

Sum Column Results in SQL

How do you sum the results of a calculated column into one number in SQL?
SELECT
id, SUM(cost + r_cost) AS Revenue
FROM
revenue_table
WHERE
signup_date >= '2015-01-01'
GROUP BY
id
ORDER BY
Revenue DESC
LIMIT 20;
This query displays the revenue to date of the top 20 customers. How can I quickly do a total sum of the Revenue to get the total Revenue of the top 20 guys?
Assuming you're using MySQL:
-- Option 1: Simply put your query in the FROM clause and sum the result
select sum(Revenue)
from (select id, sum(cost + r_cost) as Revenue
from revenue_table
where signup_date >= '2015-01-01'
group by id
order by Revenue desc
limit 20) as a
-- Option 2: Use, as suggested by Siyual in his comment, ROLLUP.
-- You'll have to use a subquery too, because
-- LIMIT is applied after the ROLLUP
select id, sum(a.Revenue) as Revenue
from (select id, sum(cost + r_cost) as Revenue
from revenue_table
where signup_date >= '2015-01-01'
group by id
order by Revenue desc
limit 20) as a
GROUP BY id WITH ROLLUP

Get the nearest/lowest Date SQL

I have four dates with a different prices for each date:
10/01/2011 $25
10/08/2011 $50
11/17/2011 $100
12/23/2011 $150
SQL:
SELECT price FROM MyTable WHERE MyDate <= '10/12/2011'
PROBLEM: This query returns $25 and $50. I need it to give me the nearest date only...
How can i have it return only the $50?
SELECT top 1 price FROM MyTable WHERE MyDate <= '10/12/2011' order by MyDate desc
Try this (in SQL Server)
SELECT TOP 1 price
FROM MyTable
WHERE myDate <= getDate()
ORDER BY myDate DESC
Try this (in mySQL)
SELECT price
FROM MyTable
WHERE myDate <= now()
ORDER BY myDate DESC
LIMIT 1