Query Values Progressivly By Month

Oct 26, 2007

I have a table with the following fields;
sub_id (unique), insertdate, buy (bit), buydate


I need to query to show count of sub_id for all fields inserted by month
from this I need to then count all fields with buy = 1 by month with each subsequent month only showing values that were contained in the previous months dataset.


The only way I can think to do this is to write a seperate query for each month that references the previous months query, but I'd like to make this as easy to maintain as possible, one query would be nice, not having to hard code the months even nicer.

Sounds a bit confusing, but hopfully you follow thanks in advance for the help.

View 2 Replies


ADVERTISEMENT

SQL Server 2012 :: Query To Find The Difference In Values From Previous Month?

Dec 12, 2013

I have my sql tables and query as shown below :

CREATE TABLE #ABC([Year] INT, [Month] INT, Stores INT);
CREATE TABLE #DEF([Year] INT, [Month] INT, SalesStores INT);
CREATE TABLE #GHI([Year] INT, [Month] INT, Products INT);
INSERT #ABC VALUES (2013,1,1);
INSERT #ABC VALUES (2013,1,2);

[code]....

I have @Year and @Month as parameters , both integers , example @Year = '2013' , @Month = '11'

SELECT T.[Year],
T.[Month]

-- select the sum for each year/month combination using a correlated subquery (each result from the main query causes another data retrieval operation to be run)
,
(SELECT SUM(Stores)
FROM #ABC
WHERE [Year] = T.[Year]
AND [Month] = T.[Month]) AS [Sum_Stores],
(SELECT SUM(SalesStores)

[code]....

What I want to do is to add more columns to the query which show the difference from the last month. as shown below. Example : The Diff beside the Sum_Stores shows the difference in the Sum_Stores from last month to this month.

Something like this :

+------+-------+------------+-----------------+-----|-----|---+-----------------
| Year | Month | Sum_Stores |Diff | Sum_SalesStores |Diff | Sum_Products |Diff|
+------+-------+------------+-----|------------+----|---- |----+--------------|
| 2013 | | | | | | | |
| 2013 | | | | | | | |
| 2013 | | | | | | | |
+------+-------+------------+-----|------------+--- |-----|----+---------| ----

View 3 Replies View Related

SQL Server 2012 :: Select Query - Get Result As Month And Values For All Months Whether Or Not Data Exists

Jul 27, 2015

I have a table with dates and values and other columns. In a proc i need to get the result as Month and the values for all the months whether or not the data exists for the month.

The Similar table would be-

create table testing(
DepDate datetime,
val int)
insert into testing values ('2014-01-10 00:00:00.000', 1)
insert into testing values ('2014-05-19 00:00:00.000', 10)
insert into testing values ('2014-08-15 00:00:00.000', 20)
insert into testing values ('2014-11-20 00:00:00.000', 30)

But in result i want the table as -

Month Value

Jan1
Febnull
Marnull
Aprnull
May10
Junnull
Julnull
Aug20
Sepnull
Octnull
Nov30
Decnull

View 9 Replies View Related

SQL 2012 :: Generating Date Range Values (start / End Dates) From Month Columns With Boolean Values

Jan 13, 2015

I've got some records like this:

ID_________Jan Feb...........................Dec
0000030257 0 0 0 0 0 0 1 1 1 1 1 0

where each month field has a 0 or 1, depending on if the person was enrolled that month.

I'm being asked to generate a table like this:

ID_________ Start_Date End_Date
0000030257 July 1, 2014 Nov 30, 2014

Is there some slam dunk way to do this without a bunch of If/Then statements?

The editor compressed all my space fields, so the column headers are off in some places.

View 8 Replies View Related

T-SQL (SS2K8) :: How To Make Sum Of Values For The Month

May 19, 2014

I've the table like

create table expense
(
bill_date datetime,
travel int,
fixed int,
food int,
lodge int
)

insert into expense values('01-04-2014',1200,250,0,0)
('02-04-2014','0',0,500,600)
('0-04-2014','800',300,0,0)

Like I've 30th onwards.....

Expecting o/p:

month Travel Fixed Food Lodge
apr-14 200 550 500 600

These cum column values how to make a code ?????

View 5 Replies View Related

SQL Server 2008 :: How To Sum Values Based On Quarter And Month

Mar 20, 2015

We had a requirement that need to sum the data based on quater we will be having 12 months data in the system for an year suppose we have 12 records for 2014 year. jan month sales data should be same when we were in feb month it should sum jan+feb sales and should show in sales column whereas we were in march month it should sum jan+feb+mar sales, then same for next quater also apr month it wil be same value in may it should be apr+may in may sales value etc ....

We will be having date column values as 201401,201402,.....

How can we implement in sql sever performance should be good.

View 1 Replies View Related

Parameter Selection Of Month, Showing Selected Month And Sum Up To That Month In Another Row

Apr 5, 2008

Hello what I'd like to display the following in a matrix report:

Parameter selected: 3 (March), 2008 (Year)

Monthly TO Summed up
ArtNo March <=March
1210 20,500 50,900
1220 21,200 64,000
1230 15,400 40,300
... ... ...

So, in the rows I have the articles and in the column the selected month via parameter. In another column I need to sum up all monthly values up to the selected month, meaning in this example the sum of jan, feb and mar per article.

View 3 Replies View Related

SQL Server 2012 :: Calculate Total On-peak And Off-values For A Month

Nov 25, 2014

SQL query to calculate the total on-peak and off-values for a month as well as the Max/highest on-peak/offPeak hourly value for that month.

On a daily basis i store the hourly values of the meter in a SQL table.

On-Peak

Summer: Apr-Oct hours(7-22) on weekdays (M-F)
Winter: Nov-Mar hours(8-23) on weekdays (M-F)

off-Peak

Summer: Apr-Oct hours(0-6,23,24); Weekends (Saturday & sunday) ; all public holidays during those months as to be considered as off peak

Winter: Nov-Mar hours(0-7,24);Weekends (Saturday & sunday); all public holidays during those months as to be considered as off peak

Here is the DB Table Structure:

Column Name & Data Types
HourId - Uniqueidentifier
CustomerName - nvarchar(50)
Readingdate - datetime
IntegratedHour - TinyInt
Load - decimal(18,4)
Generation - Decimal (18,4)
LastModified - Datetime
ModifiedBy - nvarchar(50)

View 9 Replies View Related

Create WHERE Statement That Will Calculate Values From Current Fiscal Year To Last Complete Month

Feb 3, 2015

I'm trying to create a WHERE statement that will calculate values from our current fiscal year to the last complete month.I'm using code that was created for us that does the calculations for our entire fiscal years. I thought I had fixed the WHERE statement to work like we wanted last year, but it appears to be broken now after trying it again in January and February. I'm guessing my WHERE statement only works for March and up, but how to get it to work for every month. Most attempts I'm trying it's just returning very large and inaccurate values.

I included my WHERE statement below of what I originally had that worked last year. The @BeginYear/Month/etc are retrieved from a different table and @Month is just set to MONTH(GETDATE())-1.

WHERE
(YEAR(SA3.DocumentDate)=@BeginYear AND MONTH(SA3.DocumentDate)>=@BeginMonth AND MONTH(SA3.DocumentDate)<=@Month)
OR
(YEAR(SA3.DocumentDate)=@EndYear AND MONTH(SA3.DocumentDate)<=@EndMonth AND MONTH(SA3.DocumentDate)>=@Month)

View 6 Replies View Related

Analysis :: How To Get Distinct List Of Member Values For Month Numbers From Date Dimension

Sep 10, 2015

Have a need to let the user select the year and month to use for filtering results from an MDX query that populates a report.I think all I should need is a list of years and a Month name / number.What would the filter look like if say I had a Date dimension that included the year number in a 4-digit and month in a 2-digit number?  In TSQL it would be something like ... where Month = @month AND Year = @year...How do I get a distinct list of member values for the month numbers from the Date dimension?

View 6 Replies View Related

Query By Day Of The Month

Jul 9, 2004

Looking advice on how to query for just a single day of the month. Example is for billing sent on the same day of each month, need to get all accounts that started on that day of the month no matter which month. If a account started January 7th, and it is July 7th, I would like it to list all accounts that started on the 7th day of the month. The database has a start date field in short date format.

View 1 Replies View Related

Query First Day Of Each Month

Aug 8, 2013

Is my query below the most efficient way to query the first day of each month?

SELECT base_rate, doc_pt, chgdate
FROM producthistory
WHERE chgdate IN
(
SELECT MIN(chgdate)
FROM ProductHistory
WHERE prod_id =1199812
and base_rate > 0
GROUP BY MONTH(chgdate), YEAR(chgdate)
)
AND prod_id = 1199812
ORDER BY chgdate DESC

View 5 Replies View Related

Month Name From The Sql Query

Aug 16, 2007

Hi alli want result as month name from my queryi tried with the following query but it give result as month numberlike (8)select (month(getdate())) as expri want result as month name (Augest)..give me the proper query...from Sachin

View 2 Replies View Related

SQL Query Automatically Count Month Events B4 Today; Count Events Today + Balance Of Month

Mar 20, 2004

I would like to AUTOMATICALLY count the event for the month BEFORE today

and

count the events remaining in the month (including those for today).

I can count the events remaining in the month manually with this query (today being March 20):

SELECT Count(EventID) AS [Left for Month],
FROM RECalendar
WHERE
(EventTimeBegin >= DATEADD(DAY, 1, (CONVERT(char(10), GETDATE(), 101)))
AND EventTimeBegin < DATEADD(DAY, 12, (CONVERT(char(10), GETDATE(), 101))))

Could anyone provide me with the correct syntax to count the events for the current month before today

and

to count the events remaining in the month, including today.

Thank you for your assistance in advance.

Joel

View 1 Replies View Related

Date Query Using Month Name

Mar 17, 2004

Hello,

I have made a query that does a cross-tab of data. The date data is normal like 02/04/2004, 03/04/2004 etc.

I am using Month Name to group the dates by Month name.

My problem is the query result sorts the month names in alphabetical order, not month order.

I am using the query to generate a graph and the months are not in order.

Is there a way to sort the months by month order not alphabetical order.

Thanks
Goong

View 4 Replies View Related

Sum Two Columns For Each Name/month (was SQL Query - Need Help!)

Jan 2, 2007

Can someone Please help me with what seems to me a "complex" query??

I have the following columns/data - See Original Data.jpg

This is what I need the SQL query(s) to do. I need it to
1) Select the distinct names AND months
2) Count the number of times that a name AND a month appeared together
3) Sum totalsold for each name/month
4) sum employeescore for each name/month

So it would look like - After Query.jpg

View 10 Replies View Related

Within A Month Select Query

Apr 25, 2007

elo!

actually im using interbase but id like to know the equivalent SQL code so that i can explore how to do it in interbase.

i have a table with a date field. i would like to select all entries which belong to a certain month. this is how i do it:

"select * from table WHERE (cast(datefield as varchar) like :MNT)"

:MNT is a parameter equivalent to "1/%/2007" for example for january

can you please help me convert this statement to a valid query?

"select * from table where month of datefield in [month]"

i hope you can help me.

thanks in advance

View 2 Replies View Related

Current Month Date Query

Jan 18, 2007

Hi,I have a simple table called events, which lists the start and end dates of events. I'm using a calendar control that queries the db for events, but at the moment it does a check for every day by passing in the day. (Very inefficient) What I'd like to do is pass in the current month, and get a set of rows that have an event which is in that month. It sounds easy, but I'm a little confused about what to do if the event starts current month -1 and ends currentmonth +1 I obviously need to return results like these also. 

View 4 Replies View Related

Current Month && Year Query?

Jan 18, 2007

I am writing a usage query, I need to determine what the current month and year is. If the current month is 1, then I need Year-1.  I keep getting this error Line 5: Incorrect syntax near '='.
If I comment out the case statement just evaluate the  (YEAR(User_Date) = YEAR(DATEADD(yy, - 1, GETDATE())))or (YEAR(User_Date) = YEAR(GETDATE())) by itself, the query works. What I am missing? Anybody?1    SELECT     CONVERT(char(10), User_Date, 101) AS userdate, COUNT(*) AS CNT, User_Name2    FROM         Users3    WHERE     (User_Name = 'Joe Bob') AND (MONTH(User_Date) = MONTH(DATEADD(mm, - 1, GETDATE()))) AND 4    case  MONTH(User_Date) when  1 then 5      (YEAR(User_Date) = YEAR(DATEADD(yy, - 1, GETDATE())))6    else (YEAR(User_Date) = YEAR(GETDATE()))7    END8    GROUP BY CONVERT(char(10), User_Date, 101), User_Name9    ORDER BY CONVERT(char(10), User_Date, 101), User_Name 
 

View 5 Replies View Related

Create Query To Display Month Between?

May 3, 2008

Hello everybody,I want to ask how to create query use the solve the problem of this..Example : I want to display the month january between february... Sorry if my english is not good...Thank you... 

View 3 Replies View Related

Month Date Range Query Help.

Dec 18, 2001

I need SQL to determine what the date range for the previous month was, ie
Start date 11/01/01 for 11/30/01.
The results will populate a drop down box for user queries.

View 1 Replies View Related

Count Query Breaking Down By Month

Dec 6, 2013

Need query to expand the count from a month to the entire year in 2013 .Below is my query where I got the values for a month in 2013 ,How do I expand on this query so that it generates for the entire 2013

Query
SELECT RD.RPTDESC,Count(SR.RPTDESC) AS ReportCount,sum(SR.Hrs) as ProdHours,Sum(SR.Mins) as ProdMins, (sum(SR.Hrs)*60+ Sum(SR.Mins)) as TotalProdTime,
(sum(SR.Hrs)*60+ Sum(SR.Mins)/Count(SR.RPTDESC)) as AverageProdTime,sum(SR.TriageHrs) as TriageHours,Sum(SR.TriageMins) as TriageMins,
(sum(SR.TriageHrs)*60+ Sum(SR.TriageMins)) as TotalTriageTime,(sum(SR.TriageHrs)*60+ Sum(SR.TriageMins)/Count(SR.RPTDESC)) as AverageTriageTime

[Code] ....

Results

Jan-13Feb-13
RPTDESCReportCountProdHoursProdMinsTotalProdTimeAverageProdTimeTriageHoursTriageMinsTotalTriageTimeAverageTriage
TimeReportCountProdHoursProdMinsTotalProdTimeAverageProdTimeTriageHoursTriageMinsTotalTriageTimeAverageTriageTime
20506060120252558014014017039394

[Code] ...

Also when I am running for months individually there are certain months where for certain reportids there is no data returned,I would like to populate all zeroes for that row for example report id 306 in February and how to get decimal values in average fields.

View 2 Replies View Related

Count Query Against A Column Over Last 6 Month?

Mar 3, 2015

I have a few million rows of a data in a table that store indexing information for scanned customer documents. Fields like last name, first name, document description (descript), document type and scan date (scandate).

I want to be able to query the document description column where it'll show how many times each document description was scanned/used over the course of the last 6 months or year.

View 3 Replies View Related

Replace And Date/month Query

Mar 19, 2008

SELECT CRDATE, RCTNCCRD
FROM creditcardtable
WHERE (RCTNCCRD <> '') AND (NOT (ISNULL(RCTNCCRD, '999') = '999')) AND (RCTNCCRD NOT LIKE '%x%')
ORDER BY CRDATE DESC

i want to convert any credit card numbers in creditcardtable to an obfuscated format such as:

4332 3423 5423 5428

And convert it to

XXXX XXXX XXXX 5428

HOWEVER, it will only do it if the order is older than 3 months old. Only 90 days/3 months max

how can i do that?
when i use where crcdate<90...it gives me error..
can anyone help me?

View 4 Replies View Related

Query Between Dates But Group By Month

May 22, 2008

hello, how can I query dates using "between" function but grouped by months? for example:

QUERY:
FROM: 15/DIC/2007 TO: 15/FEB/2008

RESULT:
DECEMBER-2007 --- $49,535
JANUARY-2008 --- $45,352
FEBRUARY-2008 --- $52.345

Thanks in advance-!

View 4 Replies View Related

Can Someone Write A Query To Get Last Date Of Each Month

May 19, 2008



Hello,

Can any one write a query to give the last date of each month

thanks alot PROS

View 9 Replies View Related

Specifying The Current Month In A Query/view

Jul 10, 2007

Hi, I'm dabbling in trying to retrieve some info from an SQL database and publish it in Sharepoint data view. I'm trying to create a View in the SQL database that retrieves all records for the current month. So that in July, it automatically shows me July records, and when August ticks over, it automatically displays August's records. I can hard code the dates in to the query no probs (e.g. a statement like ENTRYDATE >= '1/07/2007') but was hoping there is a way to specify current month. So maybe the statement looks like ENTRYDATE >= "CURRENTMONTH".



Thanks in advance!

View 9 Replies View Related

T-SQL (SS2K8) :: Query That Can Provide 6 Month Forecast?

Dec 17, 2014

Background is that I am recreating charts in SSRS that were being created in Excel. The source data is residing in a SQL Server database. I'm having a hard time coming up with a SQL query to provide a 6 month forecast. I can get my data into a pivot (within a stored procedure) in the following format:

Period---------Date--------------------------------Percent
1--------------2013-11-01 00:00:00.000---------0.3762
2--------------2013-12-01 00:00:00.000---------0.3584
3--------------2014-01-01 00:00:00.000---------0.3604
4--------------2014-02-01 00:00:00.000---------0.3292
5--------------2014-03-01 00:00:00.000---------0.3519

[Code] ....

I need to forecast the next 6 dates 12/1/2014 thru 5/1/2015 using the last 6 months in the data set (periods 8 thru 13)

Period---------Date--------------------------------Percent-------Forecast
1--------------2013-11-01 00:00:00.000---------0.3762
2--------------2013-12-01 00:00:00.000---------0.3584
3--------------2014-01-01 00:00:00.000---------0.3604
4--------------2014-02-01 00:00:00.000---------0.3292
5--------------2014-03-01 00:00:00.000---------0.3519
6--------------2014-04-01 00:00:00.000---------0.4064

[code].....

how to use the first table to generate the forecast values in the second table.

View 4 Replies View Related

SQL Server 2008 :: Query Grouping By Month

Mar 5, 2015

I have the query below which produces a succesful output but as there is more than one course date the month appears for example three times where there are three courses in Jan as the example output below how can I change the query to group these

MonthYear CCG AttendedCity CCG DNACity CCG Cancelled
Oct2014010
Jan2015000
Jan2015000
Jan2015100
Feb2015000
Mar2015210
May2015010

SQL QUERY
SELECT CONVERT(char(3), dbo.tblCourses.CourseDate, 0) AS Month, YEAR(dbo.tblCourses.CourseDate) AS Year, SUM(CASE WHEN a.AttendanceStatus IN (9)
THEN 1 ELSE 0 END) AS [City CCG Attended], SUM(CASE WHEN a.AttendanceStatus IN (3) THEN 1 ELSE 0 END) AS [City CCG DNA],

[Code] ....

View 2 Replies View Related

Query The Data For Month,year Range

Apr 30, 2008

Hi,


I want to display records from Jun-2006 To Mar-2008.Month and Year are two different fields.I got the expected result using Union as follows.But i want it within one qury only.Is it possible? if yes please guide me.

(Select SUM(Amt),
R.Month AS Month ,R.Year AS Year FROM Receipt R
WHERE (R.Month >= 6 AND R.Year = 2006)
Group By R.Year , R.Month )
Union
(Select SUM(Amt),
R.Month AS Month ,R.Year AS Year FROM Receipt R
WHERE (R.Month <=3 AND R.Year = 2008)
Group By R.Year , R.Month )

View 9 Replies View Related

Problem Query For Records For Previous Month

May 23, 2008

I'm working on project for school that involves building a query in a video store database. The query is suppose to pull the total number of movies rented the previous month. I can get it to work if I physically put in the dates. However, part of the requirements is to set it up so the date range is auto calculated. The following is the code I have

SELECT COUNT(RecordNumber) AS TotalRentalsForMonth FROM RentalHistory
WHERE TransactionDate BETWEEN (YEAR(getdate()), MONTH(getdate()), 1)
AND (YEAR(getdate()), MONTH(getdate())+1, 0)


I get the following error message when I try to run it:

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near ','.


Anyone have an idea where my mistake is within the date range

View 1 Replies View Related

Help With Modifying Working Query (group By Month)

May 28, 2008

Hi,

I have the following query which is working fine, but its returning a row for each day.

I'd like to modify it somehow so that we had the same data returned, but 1 row for each month. Can anyone offer some insight ?

Any help is much appreciated !!

thanks once again,
mike123






CREATE PROCEDURE [dbo].[select_Stats_LoginHistory]

(
@numDays int
)

AS SET NOCOUNT ON


SELECT CONVERT(varchar(10),LL.loginDate,112) as loginDate,
COUNT(LL.userID) AS TotalLogins,
COUNT(DISTINCT LL.userID) AS TotalLogins_Unique

FROM tblLogins_Log LL WITH (NOLOCK)
WHERE DateDiff(dd, LL.loginDate, GetDate()) < @numDays
GROUP BY CONVERT(varchar(10),LL.loginDate,112)
ORDER BY loginDate DESC


table structure below


CREATE TABLE [dbo].[tblLogins_Log](
[loginID] [int] IDENTITY(1,1) NOT NULL,
[userID] [int] NULL,
[IP] [varchar](15) NOT NULL,
[loginDate] [datetime] NOT NULL
) ON [PRIMARY]

GO

View 1 Replies View Related

Transact SQL :: Query To Get Last Available Data Given Month And Year?

Jul 21, 2015

I am in seach of a query where in I can provide month, year and client name and fetch last available comments from the table.

Client,Month,Year and Comments are columns in that table.

For Ex: If i pass client as A, month as 7 and year as 2015, I should get comments for client A, month July and year 2015 if available.

If data not available, it must go to June month and so on until it finds comments.Also when month is Jan, if query is going back, year also should get changed.

View 10 Replies View Related







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