SQL Query-Multiple date ranges - sql-server

I want to fetch some data from DB by giving multiple date ranges. Example,in February I want to get weekly report from a table in this order Feb 01 to 07, Feb 07 to 14, Feb 14 to 21, Feb 21 to 28 and Feb 28 to Mar 01. In DB the records are stored in a daily wise not in weekly wise. I want to cluster it as weekly wise and calculate sum then show the result. Please help me if you know this case.
For clear cut view, consider 3 tables & its columns.
Table A:id,timestamp (comment-data is inserted daily)
Table B:id,fruits
Table C:id,fruits_type
Result:
fruits_type count(id) timestamp
apple 3 01-02-2016 to 07-02-2016
orange 5 01-02-2016 to 07-02-2016
pineapple 8 01-02-2016 to 07-02-2016
apple 4 07-02-2016 to 14-02-2016
orange 5 07-02-2016 to 14-02-2016
Conditions:id should match among 3 tables;fetch data by providing group by fruits_type and timestamp should be in weekly wise.
Please help if you know this

To get the sum of all values between two dates you would do it like this:
SELECT SUM(Column1)
FROM Table1
WHERE Date1 BETWEEN '2/1/2016' AND Date1 <'2/7/2016'
If you want to make it more flexible and have the query get the last week's sum you can use the DATEADD function to lag by one week:
SELECT SUM(Column1)
FROM Table1
WHERE Date1 BETWEEN DATEADD(week, -1, GETDATE()) AND Date1 < GETDATE()
If you want the result set to include a row for each week, you can use UNION to merge the queries.

Related

How to generate automatic Rows

I have Below Sample Table
month year budget_Amt Actual_Amt
feb 2017 25 30
mar 2016 10 5
apr 2016 50 15
I am executing following query
select month,year,budget_amt,Actual_Amt from Table where month in('Feb','Mar','apr')
I need following output
month year budget_Amt Actual_Amt
feb 2017 25 30
mar 2016 10 5
apr 2016 50 15
QuarterYTD 2016 85 50
4th record will generate automatically when I execute query
Based on the data given, you could UNION in grouping like the following. However, I assume that your data is more complex and some additional code would need to be added to the query.
select month,year,budget_amt,Actual_Amt from Table where month in('Feb','Mar','apr')
UNION ALL
select 'QuarterYTD', Year, sum(budget_amt), sum(Actual_Amt) from Table where month in ('Feb','Mar','apr') group by Year

Create function to filter out data that meets a specific condition in SQL Server 2012

I'm creating a report in SQL Server 2012. The report is pulling out discharge patients information from database. The report only needs to show patients the third admission day information.
For example, patient A was admitted into the hospital on January 01/2016, (stayed for 4 days) January 02, January 03, January 04 and was discharged on January 05/2016.
Patient B was admitted into the hospital on January 15/2016, (stayed for 6 days) January 16, January 17, January 18, January 19, January 20 and was discharged on January 21/2016.
The report only needs to show the third day's (January 03 and January 17) information.
How to write the function to filter out the data only show necessary data? Any suggestions?
Greatly appreciate your big help!
Thanks!
Rose
You can use a combination of Row_Number() and Partition by. Basically you partition by the patient and you row_number based on the date ascending.
Select ... ROW_NUMBER() over(PARTITION BY patientId Order by TheDate)
Then you can use that above as a sub query and filter where t.theRow = 3.
Sorry I'm on an iPod so it's difficult to provide more info. I'll try to clean this up or format it tomorrow.
Edit
Now that I'm on a PC, here's what you can do per above
SELECT
t.PatientID,
t.TheNumber
FROM
(
Select
PatientID,
ROW_NUMBER() over(PARTITION BY PatientID ORDER BY YourDateField) AS TheNumber
FROM
YourTable
) t
WHERE
t.TheNumber = 3

sum up every 12 months in a table

i have a table calculating the installments. in that table i'm saving all the data recording to that. For example if i'm calculating for 60 installments and saving all the data,so it is like 60 months. so now i need to sum up the value of one column for every 12 months. sometimes v start paying the installments from the middle of the year also.
my DB looks like this.the highlighted column must sum up for every 12 months. two images are one table only
suppose i have 30 installments from starting on jun 2012.suppose i started paying installment from jun 2012 then should sum up the installments from jun 2012 to may 2013. v can't use group by year. i must sum up like this ................................................................................‌​
sum jun 2012 to may 2013
sum jun 2013 to may 2014
sum jun 2014 to nov 2014 ( only 6 months left)
You can use ROW_NUMBER to generate a group of 12 months:
WITH Cte AS(
SELECT *,
RN = (ROW_NUMBER() OVER(ORDER BY InstallmentMonth) - 1)/ 12
FROM your_table
)
SELECT
SUM(InteresetPerInstallment)
FROM Cte
GROUP BY RN

Calculate payments on a month by month bases from date opened SQL 2008

I'm currently trying to replicate an old report that used to produce a rolling sum of collections. However it wasn't a standard month on month. Here is screen shot of the excel based report.
The blue section is based on a simple query and gives the dataset used to start(EXAMPLE):
SELECT COUNT(AccountNo) AS Number, SUM(Balance) AS Value, DATENAME(MM,DateOpened) AS Month, DATEPART(Y,DateOpened) AS Year FROM tblAccounts
GROUP BY DATENAME(MM,DateOpened), DATEPART(Y,DateOpened)
The tables are very basic :
AccountNo | Balance | DateOpened
12345 | 1245.55 | 01/01/2015
I'm struggling to get it to work out the months on a rolling basis, so Month 1 for Apr 2011 will be the first month for those files (payments in April), month 2 would be payments in May for the accounts opened in April (I hope that is clear).
So this means Month 1 for April would be April, and Month 1 for Nov would be Nov. Payments are stored in a table tblPayments
AccountNo | DatePayment | PaymentValue
12345 | 02/02/2015 | 15.99
Please ask if I haven't been clear enough
Assuming you have a column called "DatePayment", you should simply do something like this:
SELECT COUNT(AccountNo) AS Number, SUM(Balance) AS Value,
DATENAME(MM,DateOpened) AS Month, DATEPART(Y,DateOpened) AS Year,
DATEDIFF(MONTH, DateOpened, DatePayment) AS MonthN
FROM [...]
GROUP BY DATENAME(MM,DateOpened), DATEPART(Y,DateOpened),
DATEDIFF(MONTH, DateOpened, DatePayment)
The DATEDIFF simply counts the months between the date the account was opened and the date of the payment. Note that you might want to change the DateOpened to always be the 1st of the month in the DATEDIFF calculation.
In the FROM [...] part of your query, you will need a join between your Payments-table and the table holding your accounts, in order to be able to compare DateOpened with DatePayment. You should join them on the AccountNo-column. This looks something like this:
FROM Accounts INNER JOIN Payments ON Accounts.AccountNo = Payments.AccountNo
After doing this, you will need to make sure that all references to columns that exist in both tables are fully qualified. This means that COUNT(AccountNo) should be changed to COUNT(Accounts.AccountNo), etc.

Dividing a value by number of days in a month in a date field in SQL table

I am working on an SQL query which performs some arithmetic division on the data in a SQL Table based on the value in a date column.
To elaborate I have the following SQL table Deals
id Date Type Quantity Price
3 2014-11-04 Sweet 2500 23
9 2014-12-04 Sweet 5000 30
10 2014-12-04 Midale 2500 25.4
11 2014-11-04 Sweet 5000 45
Now, I want to some arithmetic operations on Quantity column grouped by Type and Date.
I used the following query
SELECT
Type,
COUNT(Id) AS Trades,
SUM(Quantity ) AS M3,
ROUND((6.2898*SUM(Quantity ))/31,4) AS BBLperDay,
CAST(Date as date) AS TradeMonth,
ROUND(SUM(Quantity*Price)/Sum(Quantity),4) AS WeightedAverage
FROM Deals
GROUP BY
Type,CAST(Date as date)
The above query returns
Type Trades M3 BBLperDay TradeMonth
Sweet 2 7500 1521.7258 2014-11-04
Midale 1 2500 507.2419 2014-12-04
Sweet 1 5000 1014.4839 2014-12-04
The above results are correct but I hard coded number of days as 31 in the Date in the expression
6.2898*SUM(Quantity )/31 AS BBLperDay
Is there a way I can do just have a value taken from Date column based on the month. If the month is December in the Date column the value will automatically be 31 as number of days in december are 31.
To find no. of days in a month
Select DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,getdate()),0)))
or If you are using SQL SERVER 2012+
Select DAY(EOMONTH(getdate()))
Change your query like this.
SELECT
Type,
COUNT(Id) AS Trades,
SUM(Quantity ) AS M3,
ROUND((6.2898*SUM(Quantity ))/DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,TradeMonth),0))),4) AS BBLperDay,
CAST(Date as date) AS TradeMonth,
ROUND(SUM(Quantity*Price)/Sum(Quantity),4) AS WeightedAverage
FROM Deals
GROUP BY
Type,CAST(Date as date),TradeMonth

Resources