Transact SQL :: Get Counts Including Previous Years / Months?

May 28, 2015

I have simple query that works fine if I write it every time. I want to get this one time group by each year and week ending. here us the query:

Select count(distinct ID) from table1 where year<=2015 and WeekEnding<='05/09'

Select count(distinct ID) from table1 where year<=2015 and WeekEnding<='05/16'

Select count(distinct ID) from table1 where year<=2015 and WeekEnding<='05/23'

How can I get the count for each week year and each week ending? Weekending 05/16 will include ID's from weekending 05/09 as well and week ending 05/23 will include all the ID's from  05/16 and 05/09 and so on...

View 13 Replies


ADVERTISEMENT

Getting Density Of Values Across Years And Months

Aug 29, 2007

Hi All,

I have the following table "Project"

-------------------------------------------------------------------------------------------
ID Name Start Date End Date
--------------------------------------------------------------------------------------------
001 Project 1 2-2-2003 2-3-2007
002 Project 2 1-24-2003 2-6-2007
003 Project 3 4-10-2005 2-10-2008
004 Project 4 5-20-2006 6-6-2008
...
015 Project 15 2-20-2006 3-3-2009
----------------------------------------------------------------------------------------------
What I want is the the following output.

Output 1:

------------------------------------------------------------------------------------------------------------------------------------------------
Year Projects No. Of Projects Starting Months
------------------------------------------------------------------------------------------------------------------------------------------------
2003 Project 1 , Project 2 2 February, January
2005 Project 3 1 April
2006 Project 4, Project 15 2 May , Feb
------------------------------------------------------------------------------------------------------------------------------------------------

(the order displayed in the months shoudl be in accordance with the order of the projecs in the projects column...)
and also the following

Output 2: (this is optional view...)
-----------------------------------------------------------------------------------------
Year Start Date Project Name
-----------------------------------------------------------------------------------------
2003


February 2 Project 1
January 24 Project 2
2005
April 4 Project 3
2006
May 5 Project 4
February 20 Project 15
-------------------------------------------------------------------------------------------

I am very much in need of Output 1. Could someone help me,




View 5 Replies View Related

T-SQL Script To Convert An Integer Into Years And Months

Dec 15, 2007



Hi there,

for displaying purposes I'm trying to convert number of months into years and months. ie. 35 months = 2 years and 11 months.

how can I do this within a T-SQL script?

Thanks for your help.

Manny

View 1 Replies View Related

Display The Variance Between Two Years In Row With Months In Columns?

Mar 17, 2008

I already read a lot about the inscope-function and how it is used to display variances over time periods. But I don't know where to start, as there is no tutorial how to setup this functionality. What I want to display within the report is the following:





Code Snippet

Months
ProductGroup Article Year 1 2 3 4 5 ....
Bicycles 1020 2007 1500 2000 etc.
2008 3000 3000
Var. abs. 1500 1000
Var. % 100% 50%
1025 2007 0 1000
2008 500 1200
Var. abs. 500 200
Var. % 500% 20%
Motorcycles etc.

View 14 Replies View Related

SQL Server 2008 :: Find Patients With Age 6 Months To 5 Years

Mar 3, 2015

formula to return patients ages 6 months to 5 years?

create table dbo.TEST
(
MRN varchar(10),

[Code]....

View 6 Replies View Related

Get The Row Counts For Each Day Going Back To 6 Months (was Query Help)

Jun 15, 2006

I have a proc to get the rowcounts for the given date range.
I have to get the row counts for each day going back to 6 months on the table.

With this proc i can get one day's row couts.. i need to loop through for all dates.

Please can someone get me the code for this.



create proc p_rowcounts

@Date1 datetime,
@Date2 datetime

SELECT
count (*) as 'Number of Rows', @Date1 as Date
FROM
Table1 (nolock)
WHERE ModifyTime >= @Date1 and ModifyTime < @Date2

thanks for the help.

View 3 Replies View Related

SQL Server 2012 :: Get Previous Years Holiday Date?

Jan 6, 2015

Given this table;

DECLARE @table TABLE (HolidayDate DATE, HolidayName NVARCHAR(50))
INSERT INTO @table
( HolidayDate, HolidayName )
VALUES ('2012-01-01','New Years Day'),
('2012-01-16', 'MLK Day'),
('2012-02-20', 'Presidents Day'),

[code]....

How to get a result set that shows a new column called PreviousHolidayDate with the corresponding holidays last years date?

HolidayDateHolidayNamePreviousHolidayDate
1/1/2012New Years DayNULL
1/16/2012MLK DayNULL
2/20/2012Presidents DayNULL
4/6/2012Good FridayNULL
5/28/2012Memorial DayNULL

[code]....

View 4 Replies View Related

Previous Months

Mar 19, 2007

I have a View there I need my criteria to select 13 months from previous month.

Example. This is 3/1/2007 - I need to query 2/1/2007 to 2/1/2006.

View 7 Replies View Related

Calculate A Sum For The Previous Three Months?

Sep 15, 2015

Is there an easy way to calculate a sum for the previous three months?

Data
Date,Area,PropertyID,Volume,DaysInMonth
197904,6,888888,9589,30
197905,6,888888,27403,31
197906,6,888888,17130,30
197907,6,888888,14321,31
197908,6,888888,15234,31

[Code] .....

Desired Output

Date,Area,PropertyID,Volume,DaysInMonth,3MonthSum, DaysInMonthSUm
197904,6,888888,9589,30,NULL,NULL
197905,6,888888,27403,31,NULL,NULL
197906,6,888888,17130,30,NULL,NULL
197907,6,888888,14321,31,54122,91
197908,6,888888,15234,31,58854,92

[Code] .....

View 2 Replies View Related

Get Current Month And Previous 2 Months

Feb 10, 2014

I have table 'Open_Months' as shown below

Emp_IdMonthYear
00FBG 42013

I need current month and previous 2 months, for this i have concatinated month and year column into date formate, the query for this as shown below

SELECT cast(CONVERT(datetime, CONVERT(varchar(4), OM_Year) + RIGHT('0' + CONVERT(varchar(2), OM_Month), 2) + '01', 112) AS Datetime) from Open_Months where OM_Emp_ID = '00FBG'

Date
2013-04-01

From the above date I need to find current month and its previous 2 months.

View 1 Replies View Related

Extract Data For Last Day Of Previous Months

Jun 12, 2014

I need to extract records for the last day of previous months (Up till January of the same year) from a table SALES, according to a date parameter ASOFDATE that the user enters.

For Example

If user keys in ASOFDATE as 10-May-2014, I would have

ASOFDATE Data1 Data2
10-MAY-2014 123 443
30-APR-2014 222 234
31-MAR-2014 544 875
28-FEB-2014 546 908
31-JAN-2014 957 896

How do I do that?

View 2 Replies View Related

Rolling Sum To Find Total Of 3 Previous Months Gas Production

Nov 5, 2012

I'm in need of creating a rolling sum to find the sum of 3 previous months gas production. Below is an example of the basic data I will be using to find the sum.

OperatorIDRRCID YearReported MonthReported YearCode DateReported GasProduction
71054993207201222012022012-02-01 89
71054993207201212012012012-01-01 721
710549932072011122011122011-12-01 353
710549932072011112011112011-11-01 409
710549932072011102011102011-10-01 544
71054993207201192011092011-09-01 707
71054993207201182011082011-08-01 506
71054993207201172011072011-07-01 536
71054993207201162011062011-06-01 472

I want the sum of the Year & Month of 2012-2 to be the sum of the gas production for 2012-1, 2011-12, and 2011-11.

View 1 Replies View Related

T-SQL (SS2K8) :: Date Logic - How To Get Previous 6 Months Data

Sep 29, 2014

I am working in sqlserver 2008 R2 and below is my sample research query. I am trying to get previous 6 months data.

WITH CutomMonths
AS (
SELECT UPPER(convert(VARCHAR(3), datename(month, DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) - N, 0)))) Month
,DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) - N, 0) startdate
,DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) - N + 1, 0) enddate
FROM (
VALUES (1)

[Code] ...

Current output what i am getting:

Expected Output:

I found why the April month i didn't get the $20 because the startdate of my perks CTE '2014-04-03'. If it is '2014-04-01' then i will get the expected output.

But i should not change the the date on perks. How to neglect this date issue and consider the month instead to get the expected output.

View 6 Replies View Related

How To Show 6 Previous Months In A Table Based On An Input Month

Nov 3, 1999

I do appreciat your help, I want to run a store procedure which will show 6 months . I do not know how to write the procedure, here in the notion in my mind, I want to be able to pass an input parameter (month) to the procedure which will then run a query to show 6 months prior the input parameter month, how can I do that, thanks for your help

Ali

View 2 Replies View Related

T-SQL (SS2K8) :: Pass Dates For Previous Months Start And End Date

Mar 16, 2015

I've SSRS sales report to which I need to pass the dates for previous month's start date and end date which I am able to pass using below code. However, since the sales report has data from the past year(2014) I need to pass the dates for last year as well. The below code gives StartDate1 as 2015-02-01 and EndDate1 as 2015-02-28. I need to get the dates for past year like 2014-02-01 as StartDate2 and 2014-02-28 as EndDate2

SELECT DATEADD(MONTH, DATEDIFF(MONTH, '19000201', GETDATE()), '19000101') AS StartDate1,
DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()), '18991231') AS EndDate1

View 1 Replies View Related

SQL Server 2012 :: Generate Months Based On Previous Values

Jul 7, 2015

I have a data that with month values ranging from jan 2012 till july 2013 with some values associated with it.

I want to generate months automatically after july 2013 till december 2013 in sql something like the below one:

Is there a way in sql to do this?

View 2 Replies View Related

Reporting Services :: Displaying Previous Months On The Basis Of Start Date

Nov 4, 2015

I have a ssrs report which has a parameter start date.i have made 12 columns acc to client req which i cannot change:

jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec

These columns are dynamic acc to start date for which i have used this exp for first cell:

=monthname(month(Parameters!Startdate.Value),true) and for next 11 cells accordingly.

These 12 columns are grouped quaterly which i have made statically again for clien req which i cannot change so they are grouped staticaly by me in report like:

q12015      |q2  2015     |q32015      |q42015
jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec  

exp for quarterly is :

="Q" & DatePart(DateInterval.Quarter, Parameters!Startdate.Value) &  year(Parameters!Startdate.Value).

Now when i select my start date of months jan,apr,july and oct report work fine.... but when i select my start date months of feb,may,aug and nov then reportis something like: (lets say i choose feb)

q12015        |q22015     |q32015      |q42015
feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec|jan.

What is happening is in q1 feb,mar and apr are coming and what i want in q1 is jan,feb and mar.

And in q4 nov ,dec and jan is coming and what is want in  q4 is oct,nov and dec.

So generally what is am asking is how to display jan in this condition in my first cell.same apllies for rest of months..

Similarly when i select my start date months of mar,june,sep,dec i want previous two months to be displayed.

View 5 Replies View Related

SQL Server 2012 :: Sales Over Years - Retrieve Values In Single Query For Multiple Years And Grand Total?

Apr 24, 2015

I need to list customers in a table that represents sales over the years.

I have tables:

Customers -> id | name |...
Orders -> id | idCustomer | date | ...
Products -> id | idOrder | unitprice | quantity | ...

I am using this SQL but it only gets one year:

SELECT customers.name , SUM(unitprice*qt) AS total
FROM Products
INNER JOIN Orders ON Orders.id = Products.idOrder
INNER JOIN Customers ON Customers.id = Orders.idCustomer
WHERE year(date)=2014
GROUP BY customers.name
ORDER BY 2 DESC

I need something like this:

customer | total sales 204 | total sales | 2015 | total sales (2014 + 2015)
--------
customer A | 1000$ | 2000$ | 3000$
customer B | 100$ | 100$ | 200$

Is it possible to retrieve these values in a single SQL query for multiple years and grand total?

View 6 Replies View Related

Transact SQL :: Extracting From 3 Related Tables And Including MAX Function

Oct 5, 2015

I have these 3 tables in a database for printed chamber music works:

Table INSTRUMENTS: List of musical instruments
    Column ID          -- int, primary key
    Column sInstrument -- string

Table PTRS_INSTRUMENTATION: 
    Column ID          -- int, primary key
    Column lInstrument -- int, points to a row in table INSTRUMENTS via ID
    Column lMainItem   -- int, points to a row in table MAINITEMS via ID
    Column lInstrSeqNum -- int, sequential number of like instruments within one Main Item
    
Table MAINITEMS: List of chamber music works
    Column ID          -- int, primary key
    Column sItem       -- string
    
Each chamber music work (Main Item) requires an ensemble of musicians playing several instruments. Some of them may be the same, such as 2 violins. A classical quartet, for instance, consist of 2 violins, 1 viola and 1 cello. I am concerned here only with one of the instruments (although it may occur several times).

I want to extract a list of Main Items where the instrument is given (e.g., 'violin'),

And the maximum of PTRS_INSTRUMENTATION.lInstrSeqNum is a given number (e.g., 2).

View 7 Replies View Related

Transact SQL :: Select All Days In Week Number X Including Last Year If Necessary

May 24, 2015

SQL express 2012. I am trying to case in the where part and having a syntax errors - This is what i am trying to do:

select all the days in week number x including last year if necessary... so if the year start not at the beginning of the week then look in last year as well ( for the same week number of this year and last week nu of last year)

declare
@yyyy int = 2014,-- THE YEAR
@mm int = 1,-- THE MONTH
@week1No int = 1,-- THE WEEK NUMBER IN THE YEAR
@week2No int = 37-- THE last WEEK NUMBER IN last YEAR
select count(tblDay.start)-- tblDay.start IS smallDatetime

[Code] ....

View 2 Replies View Related

Transact SQL :: Trigger Saves Modifications On Table Including UserID Of One Who Does The Changes

Jun 24, 2015

How can i pass my .net application's Userid to the trigger? I have a audit trail trigger on myTable. I dont know how to pass the userid (not the sql server user) to the trigger when a user delete a record from the application(.NET Application).

The trigger saves the modifications on the table including the userid of one who does the changes.

View 4 Replies View Related

Transact SQL :: Select All The Days In Week Number X Including Last Year If Necessary

May 24, 2015

SQL express 2012

I am trying to case in the where part and having a syntax errors - this is what i am trying to do:

Select all the days in week number x including last year if necessary... so if the year start not at the beginning of the week then look in last year as well ( for the same week number of this year and last week nu of last year)

declare
@yyyy int = 2014,-- THE YEAR
@mm int = 1,-- THE MONTH
@week1No int = 1,-- THE WEEK NUMBER IN THE YEAR
@week2No int = 37-- THE last WEEK NUMBER IN last YEAR
select count(tblDay.start)-- tblDay.start IS smallDatetime

[Code] ...

View 2 Replies View Related

Transact SQL :: Finding Unique Counts Based On Consecutive Days?

Jul 9, 2015

I have a scenario here where the data looks like -

ID        Date
100      07/01
100     07/02
100    07/03
100   08/01
100   08/02
100   08/15

Now I need to find out unique occurrences of ID - 100 ( where count = unique only if the occurrences are in consecutive days, gap of even 1 day causes it to be a different instance ) - SO with the above data I should have unique occurrences as 3.efficient way to calculate this ?

View 5 Replies View Related

Transact SQL :: Aggregate Last 12 Months

Sep 2, 2015

I have a table with sample data as shown in the table below. for each month end date, I need to aggregate (sum) all the quantities for each product and customer and include the current month plus the past 12 months (including current month). 

For example, for customer C123, P123 and for 7/31/2015, the query should add 7/31/2015 quantity and the quantity for 1/31/2015. 

DECLARE @TEMP TABLE (Customer VARCHAR (10), Product VARCHAR(10), Month_end_date DATE, Quantity INT)
INSERT INTO @TEMP VALUES ('C123','P123','1/31/2015',10)
INSERT INTO @TEMP VALUES ('C124','P124','2/28/2015',20)
INSERT INTO @TEMP VALUES ('C125','P125','3/31/2015',30)
INSERT INTO @TEMP VALUES ('C126','P126','4/30/2015',40)

[Code] ....

the output for the above example should be
C123 P123 7/31/2015
 70+10=80

is this possible?

View 10 Replies View Related

Transact SQL :: Getting Data For Last 3 Months

Oct 14, 2015

I have a date into format YYYYMM. Data type is int. I need to make query where every time it will return me last 3 months, but without current one. For example I have data for months below

201510
201509
201508
201507

Query should return all records for 201509, 201508, 201507.

I was trying lot of solutions founded in internet like this one:

Date_Column >= DATEADD(MONTH, -3, GETDATE())
or
DATEDIFF(MONTH, my_date_column, GETDATE()) <= 3

but it doesn't work.

View 4 Replies View Related

Transact SQL :: Pulling The Most Recent 12 Months Of Data

Jul 1, 2015

My goal is to show the most recent 12 months of data including the current month based on a patients discharge date (relative to the query execution time). There could be many years of data so I want to be sure I am pulling the most recent 12 monthsThis seems to work (on the surface anyway … not quite sure if this is the best logic to use).

DATEDIFF(month,PAT_ENC_HSP_discharged.HOSP_DISCH_TIME,
GEtDate())
< 13

View 5 Replies View Related

Transact SQL :: Number Of Distinct Users In Last 3 / 6 / 9 / 12 Months

Aug 26, 2015

I have table A(year int, month int, user varchar(20)), and I am trying to write a view that would show number of distinct users in the last 3 months, last 6 months, last 9 months and last 12 months(all from the most recent year/month) in following format:

3 months     6 months     9 months     12  months

number of distinct users        x                  y                  z                      w

View 20 Replies View Related

Transact SQL :: Last Record Not In Past 9 Months From Todays Date?

Aug 20, 2015

I would like to display Car records to retrieve last Maintenance request for all customer who did not make request in past 9 months from current date.

MC refers to Maintenance.

MCLog data:

carId: SGY12345 (repeated)
mcDate: 2010-01-30
mcDate: 2012-03-30
carId: SGX55661 (repeated)
mcDate: 2015-05-30
mcDate: 2015-06-15

[Code] .....

Here is my Table:

CREATE TABLE Car (
carId Char (20) NOT NULL,
model Char (20) NOT NULL,
importDate smalldatetime NOT NULL,
custId Varchar (50) NOT NULL,
CONSTRAINT Car_PK PRIMARY KEY (carId));

[code]....

View 6 Replies View Related

Transact SQL :: How To Convert Hours To Days And Months Correctly

Oct 13, 2015

I get a column in hours in a table and when I try to convert it to months and days its giving me incorrect results.

My timehours column in my table has hours recorded timehours value is 5832 and I get results as 11 months and 27 days.

This query is giving me wrong result -select months=(timehours %365)/30,days= (timehours % 365)%30 

View 13 Replies View Related

Transact SQL :: Making Hours Into Months And Days In 2008 R2?

Aug 5, 2015

I have hours which can be like 32.5 and would like to have them in 1 month 2 Days format.

View 2 Replies View Related

Transact SQL :: First And Last Day Of Previous Month From Getdate

Dec 10, 2010

How to get First day of previous month and last day of previous month(From getdate()) using SQL..?

View 13 Replies View Related

Transact SQL :: Replacing Isnull With Previous Value

May 25, 2015

I am having table like below,

Period Pointvaluemonth area
NULLNULLNULLApril tn
NULLNULLNULLMaytn
NULLNULLNULLJunetn
NULLNULLNULLJulytn
NULLNULLNULLAugusttn
201109 100 10Septembertn

[Code] ....

Then i want to copy september value for october and november and Jan value for feb & mar like next null values should get replaced with previous not null value ...

My desired output is ,

Expected Output is…..

Period Pointvaluemonth area
NULLNULLNULLApril tn
NULLNULLNULLMay tn
NULLNULLNULLJune tn
NULLNULLNULLJuly tn
NULLNULLNULLAugust tn
201109 100 10September tn

[Code] ....

View 7 Replies View Related

Transact SQL :: Copy Previous Non Null Value

Aug 10, 2015

I have a table with data like below

SampleDateTime Value

2015-08-08 01:00 AM 0.5
2015-08-08 02:00 AM Null
2015-08-08 03:00 AM Null
2015-08-08 04:00 AM Null

[code]....

Using subquery I thought of a couple of ways but that didn't work.

View 6 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved