How to write query summing? - sql

i have table with 2 columns: date and points. I want to create a query that will return the sum of points for all days, including today. This is to generate a chart of points earned up and until today.
Edit: I think my question was clearer before ews edited it :)
With data like that
2012-01-01 1
2012-01-02 1
2012-01-02 2 same day as above (we can have many records for one day, you can think of it as a result of one game on that day)
2012-01-03 -1
I would like to see the result:
2012-01-01 1
2012-01-02 4 (1+1+2)
2012-01-03 3 (1+1+2-1)
I'm using SQL Server 2008. If you know how to do it in LINQ to Entities that would be great.

If you need cummulative, you should try this:
Edit:
SELECT
Date,
(SELECT SUM(Point) FROM A WHERE Date <= MainTable.Date) AS Points
FROM A MainTable
GROUP BY Date
Here is an SQL Fiddle to test it.

Some DBMSes have a better way to do this by using window functions, but here's a query that should work in most any SQL database:
SELECT t1.date,
SUM(t2.points) AS points_to_date
FROM table_name t1
JOIN table_name t2
ON t2.date <= t1.date
ORDER
BY t1.date
;

The only way I know to do this is with a new query for each day.
dateVariable = "2012-09-06"
SELECT Sum(points) From table_name WHERE Date<=dateVariable;
Obviously you would need to iterate over all the days to do this, changing dateVariable each time.

What I understand from the question you want a running sum of points, so that each date has the sum of points of all dates less than that date. If so, take a look at the running total section of this article.

Related

SQL minimum date value after today's date Now()

I am writing a query and am having trouble filtering data as I would like. In the table, there is a date field and an ItemCode field. I would like to return one record per ItemCode with the earliest date that is after today.
If today is 6/6/2017 and my data looks like:
ItemCode Date
1 6/1/2017
1 6/7/2017
1 6/10/2017
2 6/2/2017
2 6/8/2017
2 6/15/2017
I would want the result to be
ItemCode Date
1 6/7/2017
2 6/8/2017
My query so far is:
SELECT PO_PurchaseOrderDetail.ItemCode, Min(PO_PurchaseOrderDetail.RequiredDate) AS NextPO
FROM PO_PurchaseOrderDetail
GROUP BY PO_PurchaseOrderDetail.ItemCode
HAVING (((Min(PO_PurchaseOrderDetail.RequiredDate))>=Now()));
The problem is that the Min function fires first and grabs the earliest dates per ItemCode, which are before today. Then the >=Now() is evaluated and because the min dates are before today, the query returns nothing.
I've tried putting the >=Now() inside the min function in the HAVING part of the query but it does not change the result.
My structure is wrong and I would appreciate any advice. Thanks!
I would approach like this for standard SQL, Access approach may vary
select PO_PurchaseOrderDetail.ItemCode,
min(PO_PurchaseOrderDetail.RequiredDate) as NextPO
from PO_PurchaseOrderDetail
where PO_PurchaseOrderDetail.RequiredDate >= Now()
group by PO_PurchaseOrderDetail.ItemCode;
Put the date condition in the where clause (not the having clause):
select ItemCode, min(Date) as NextPO
from PO_PurchaseOrderDetail
where Date > '6/6/2017'
group by ItemCode

SQL find period that contain dates of specific year

I have a table (lets call it AAA) containing 3 colums ID,DateFrom,DateTo
I want to write a query to return all the records that contain (even 1 day) within the period DateFrom-DateTo of a specific year (eg 2016).
I am using SQL Server 2005
Thank you
Another way is this:
SELECT <columns list>
FROM AAA
WHERE DateFrom <= '2016-12-31' AND DateTo >= '2016-01-01'
If you have an index on DateFrom and DateTo, this query allows Sql-Server to use that index, unlike the query in Max xaM's answer.
On a small table you will probably see no difference but on a large one there can be a big performance hit using that query, since Sql-Server can't use an index if the column in the where clause is inside a function
Try this:
SELECT * FROM AAA
WHERE DATEPART(YEAR,DateFrom)=2016 OR DATEPART(YEAR,DateTo)=2016
Well you can use the following query
select * from Table1
WHERE DateDiff(day,DateFrom,DateTo)>0
AND YEAR(DateFrom) = YEAR(DateTo)
And here is the result:
Enjoy :D !

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 - Finding largest period of activity by customer

I had a difficult time w/ the title, hope this is a little clearer...
I have a table of data (simplified) like so;
Date
Customer
Amount
1/1/2014
1
100.5
4/4/2014
1
122.5
2/1/2014
3
3.25
...but just short of a million records.
I would like to find the x day (let's say 90) period for each customer that has the largest total amount.
To phase the question a little differently, given all the transactions for all customers, for each customer I would like to find the 90 day period that has the largest total amount and what that total amount is in the period.
Trying to advise a brute force approach where I define all the possible ranges (or iterate over all possible ranges on the fly).
Any thoughts on a more elegant solution?
You can use a self-join for this, but the performance may not be so great:
select t.*,
(select sum(t2.amount)
from table t2
where t2.customer = t.customer and
t2.date >= dateadd(day, -90, t.date) and t2.date <= t.date
) as amount90
from table t;
There is a more efficient method in SQL Server 2012.
Here's a psuedo-code ish kind of answer that I think would work. It'd probably be really slow though.
You could have a function that calculates the number of activities provided a start date and number of days,
--function F
#userid, #startdate, #dayCount
SELECT COUNT(*)
FROM TABLE
WHERE
UserID = #userid
and date > #startDate
and date < Dateadd(#startdate, #dayCount)
and then do a max on that function?
select max(f(user, date))
from TableContainingDateRanges

How to write a sql query to sum total for each day?

Please help me to write the following sql. I have a table like this, with an amount column and date column
amount date
-----------------------
100 - 2010-02-05
200 - 2010-02-05
50 - 2010-02-06
10 - 2010-02-06
10 2010-02-07
what I want is to write a sql to get total for each day. Ultimately my query should return something like this
amount date
-----------------
300 - 2010-02-05
60 - 2010-02-06
10 - 2010-02-07
Please note that now it has group by dates and amounts are summed for that date.
RESOLVED -
This was my bad, even though I mention the date column as date here, my actual date column in postgres table was 'timestamp'. Once I changed it to get the date only, everything got working
my working sql is like this "select sum(amount), date(date)
from bills
group by date(date)
"
thanks everyone (and I will accept the 1st answer as the correct answer since I can accept only one answer)
thanks again
sameera
Pretty basic group by statement.
SELECT SUM(table.amount), table.date
FROM table
GROUP BY table.date
http://www.w3schools.com/sql/sql_groupby.asp
Look into GROUPING by date, here: http://www.w3schools.com/sql/sql_groupby.asp
and look into SUM(), here: http://www.w3schools.com/sql/sql_func_sum.asp
You will need to use both of them.
Try this:
SELECT SUM(Amount), Date FROM Table
GROUP BY Date
SELECT SUM(amount) as amount_sum, date FROM table GROUP BY date;