T-SQL (SS2K8) :: Return Value In A Status Field Which Has Latest Year And Month
May 11, 2015
I have table in which month & year are stored, Like this
Month Year
10 2014
11 2014
12 2014
1 2015
2 2015
3 2015
4 2015
I wanted a query in which it should return the value in a status field which has latest year & month.
View 9 Replies
ADVERTISEMENT
Sep 10, 2014
This is my table and data
CVID | WorkExperience
--------------------------------
2838736
68181101
96568122
1135484
I need to convert into this result
CVID | WorkExperience
--------------------------------
283873 years
681818 years 5 months
9656812 years 2 months
1135484 months
View 5 Replies
View Related
Feb 22, 2015
I m creating P&L(profit and Loss ) Reports of accounts its consists of 2 levels
in level2:
my procedure display the output of (Actuals in lakhs)
RESPONSIBILITY DEPT CATEGORY CURRENT YTD ACTUALS
SALES Sales Net Sales 444.65
Sales Sales LESS TRD 22.55
SALES NET RETURNS NET RETURNS 422.10 (net sales - TRD)
Finance LESS ED LESS ED 40
Sales Totals Sales 382.10(RETURNS - ED)
(only calculation for above dept only remaining dept values display sum of relvenat accounts ,and if i click the category relvent account codes shown here)
Materials .... ... ..
production ..... ............ ........
i made a procedure for above
create procedure Pl_level2
@fmdate datetime,
@todate datetime,
@category varchar(200)
as
begin
create table #temp1
[code]....
like i m inserted so many accounts in temp tables .
IF (@category IS NULL or @catagory=' ' )
begin
select
responsibility,
dept,
category,
round(Max(Actuals)/100000,1,2) as Actuals from #temp
[code]....
here i can display only current YTD only how to display previous year (13-14) YTD in level1
How to do?
View 1 Replies
View Related
Oct 15, 2014
This statement adds two additional months to which is fine :
DATENAME(MM,dd.date)+ ' ' + DATENAME(D,dd.date) + ', ' + DATENAME(YY,dd.date)
but if my month is November and two months is added, the year does not change, it stays the same. how do I make the year change when two months are added toward the end of the year.
View 7 Replies
View Related
Mar 25, 2014
I'm trying to write some T-SQL to return the previous even numbered month and appropriate year from given date.
Examples given:
03-25-2014 should return 02-xx-2014
01-01-2014 should return 12-xx-2013
View 2 Replies
View Related
Jan 12, 2006
Hello All,I've got a DATETIME field, and it includes hour:minutes:second data. I want to do selects where I can simply match on the month, day and year. For instance, something like this:SELECT * FROM QuizAttempts WHERE DateTimeTaken = '1/12/2006'And have it match anything that was taken that day, regardless of *when* it was taken. Any suggestions?Thanks! -Josh
View 2 Replies
View Related
Mar 30, 2015
how to return the 3 month rolling average count per username? This means, that if jan = 4, feb = 5, mar = 5, then 3 month rolling average will be 7 in April. And if apr = 6, the May rolling average will be 8.
Columns are four:
username, current_tenure, move_in_date, and count.
DDL (create script generated by SSMS from sample table I created, which is why the move_in_date is in hex form. When run it's converted to date. Total size of table 22 rows, 4 columns.)
CREATE TABLE [dbo].[countHistory](
[username] [varchar](50) NULL,
[current_tenure] [int] NULL,
[move_in_date] [smalldatetime] NULL,
[Cnt_Lead_id] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
[code]....
View 9 Replies
View Related
Dec 11, 2006
i have some classes that I want to group by month/year (note:i dont need the day of the month)
how do i wirte my sql so it only gives me the dictinct groups month/year of the classes I have so that it comes out like so..
11/2006
12/2006
1/2007
3/2007
i try with my sql below but i cant get the groups th come out in order. i dont think it sees it as a date value.
dbo.classgiven.classdate date of the class.thank you all
SELECT DISTINCT { fn MONTH(dbo.classgiven.classdate) } " + "/" + "{ fn YEAR(dbo.classgiven.classdate) } AS monthyear,{ fn MONTH(dbo.classgiven.classdate) } AS monthcode FROM dbo.classT INNER JOIN dbo.classgiven ON dbo.classT.classcode = dbo.classgiven.classcode WHERE (dbo.classT.discount = '-1') AND (dbo.classT.coned IS NOT NULL)", conNorthwind )
View 9 Replies
View Related
Oct 26, 2006
Does anyone know of a way to use a funtion for returning records based on fiscal reporting periods like Quickbooks uses for example "This Month", "Last Month", "This Quarter", "Last Quarter", "This Year", "Last Year". While I realize that I can create a very long date time parsing routine for this but it is not very elegant or useful. I thought there might be a way to do this already with an existing function.I have created a stored procedure that I pass a @ViewRange Parameter to and it returns the records that I want but I need this ability in several procedures and wanted to turn it into a stored procedure.IF @ViewRange = 'This Month' SELECT TOP 20 Customer.LastName AS Customer, SUM(Sales.AmtCharge) AS Amount FROM Customer INNER JOIN Sales ON Customer.CustNo = Sales.CustNo WHERE (MONTH(Sales.InvDate) = MONTH(CURRENT_TIMESTAMP)) AND (YEAR(Sales.InvDate) = YEAR(CURRENT_TIMESTAMP)) GROUP BY Customer.LastName ORDER BY SUM(Sales.AmtCharge) DESC;IF @ViewRange = 'Last Month' SELECT TOP 20 Customer.LastName AS Customer, Sum(Sales.AmtCharge) AS Amount FROM Customer INNER JOIN Sales ON Customer.CustNo = Sales.CustNo WHERE(MONTH(Sales.InvDate) = MONTH(CURRENT_TIMESTAMP) - 1) And (YEAR(Sales.InvDate) = YEAR(CURRENT_TIMESTAMP)) GROUP BY Customer.LastName ORDER BY Sum(Sales.AmtCharge) DESC; Any ideas?
View 8 Replies
View Related
Sep 18, 2013
I have the following script that calculates Sales by month and current year.
We run a Fiscal year from April 1st thru March 31st.
So April 2012 sales are considered Fiscal Year 2013.
Is there a way I can alter this script to get Fiscal Year Totals?
select ClassificationId, YEAR(inv_dt) as Year, cus_no,
isnull(sum(case when month(inv_dt) = 4 then salesamt end),0) as 'Apr',
isnull(sum(case when month(inv_dt) = 5 then salesamt end),0) as 'May',
isnull(sum(case when month(inv_dt) = 6 then salesamt end),0) as 'Jun',
isnull(sum(case when month(inv_dt) = 7 then salesamt end),0) as 'Jul',
[Code] ....
Data returned looks like the following.
ClassificationID Year Cus_no Apr May June ....
100 2012 100 $23 $30 $400
100 2013 100 $40 $45 $600
What I would need is anything greater than or equal to April to show in the next years row.
View 2 Replies
View Related
Aug 30, 2004
I have three web form controls, a ddl that contains the day, another ddl that contains the month and a textbox that contains the current year. To send the date chosen by the user to the database, I join the three web form control values so that the resultant string is ‘day/month/year’ thus:
CmdInsert.Parameters("@Date").Value = day.SelectedItem.Value + "/" + month.SelectedItem.Value + "/" + year.Text()
And the resultant string is: dd/mm/yyyy, for example 30/08/2004.
But the problem is if the user does not select any day or any day and month, then the resultant string is for example; 00/08/2004 or 00/00/2004, but the problem is the database does not accept this format as datetime. How can I do it?
I want the user has the possibility to chose as well only the month and year, and as well only the year. Is it possible to send to the database the datetime format with only the month and year, or only the year?
Thank you,
Cesar
View 4 Replies
View Related
Feb 25, 2004
I'm using PHP with SQLServer2k to create a page containing monthly counts of episodes at a facility occurring between two user selected month/year combinations. For instance, the user could select 10/2003 and 2/2004 and facility X and get a line for each month showing the count of episodes occuring in that month.
The problem is that the episode date is stored in three integer fields (epiday, epimonth, epiyear) and I'm having a terrible time getting them into a format where I can use them in a between statement.
I've tried evaluating the parts of the episode date seperately like:
where
(epimonth>=10 and epiyear=2003)
or
(epimonth<=2 and epiyear=2004)
and that works, but what happens when someone wants to see from 10/2002 to 2/2004?
Any suggestions on the best way to do this?
View 5 Replies
View Related
Feb 2, 2004
I am trying to get my db to return a date in the format day/month/year but its returning the american version month/day/year.
I'm using a DatePart function that converts my date:
CREATE FUNCTION dbo.DatePart
( @fDate datetime )
RETURNS varchar(10)
AS
BEGIN
RETURN ( CONVERT(varchar(10),@fDate,101) )
END
This returns te american version, can anyone help me to get this to convert the UK way.
Thanks
View 3 Replies
View Related
Mar 21, 2007
Greeting guys, does anyone here experience the problem that I had currently. I did set up a mirroring for my db for 1 month + and work perfectly. However, due to lack of stability on line connection on the principal database side, so makes mirror side get disconnected frequently. I found that once the principal side get back smooth, the mirroring status shows 'synchronizing' status and I thought it gets fine again.
However, after 2 days (which more than 48 hours) and I check back the status, it still showing 'synchronizing' and synchronize slowly. It's impossible that the mirror side takes more than 2 days for synchonizing. ( Size on principal size is around 1.2GB and mirror side around 800MB) Is there any solution on it ? Is it have to re-set up the mirroring session again? I don't think is line connection issue because I did set up another mirroring session between these two servers and work fine. Hope you guys can help me out asap. Thx.
Best Regards,
Hans
View 3 Replies
View Related
Apr 24, 2007
I would like some help creating a view that will display the latest status for each application. The lastest status should be based on CreateDt.
For example:
Table Structure:
============
Application: ApplicationID, Name, Address, City, State, Zip, etc..
ApplicationAction: ApplicationActionID, ApplicationID, Status (Ex:new, reviewed, approved, closed), CreateDt
View should display:
==============
ApplicantID, ApplicantActionID, Status, CreateDt
Example:
==========
ApplicantID=4, Name=Bob Smith, etc....
ApplicantActionID=1, ApplicantID=4, Status=New, CreatDt=1/3/20071:00
ApplicantActionID=2, ApplicantID=4, Status=Reviewed, CreatDt=1/3/2007 2:00
ApplicantActionID=3, ApplicantID=4, Status=Approved, CreatDt=1/4/2007 1:00
.... etc....
View should return:
Applicant=4, ApplicantActionID=3, Status=Approved, CreatDt=1/4/2007 1:00
etc....
View 4 Replies
View Related
May 14, 2007
Hey folks, I'm looking at making the following query more efficientpotentially using the ranking functions and I'd like some advice fromthe gurus. The purpose of the following is to have a status for aperson, and also have a historical background as to what they've done,status wise. This was the best way I could come up with to do this afew years back, but I'm wondering if there's a better way with Sql2005.Here's a toned down structure and my query. Any help/critique wouldbe greatly appreciated.CREATE TABLE #Status(StatusID int NOT NULL,StatusName VARCHAR(50) NOT NULL,StatusCategoryID int NOT NULL) ON [PRIMARY]CREATE TABLE #RegStatus([RegistrationID] [uniqueidentifier] NOT NULL,[StatusID] [int] NOT NULL,[StatusTimeStamp] [datetime] NOT NULL,[UniqueRowID] [int] IDENTITY(1,1) NOT NULL) ON [PRIMARY]SET NOCOUNT onINSERT INTO #Status VALUES(200, 'StatusA', 1)INSERT INTO #Status VALUES(210, 'StatusB', 1)INSERT INTO #Status VALUES(115, 'StatusC', 1)INSERT INTO #Status VALUES(112, 'StatusD', 1)INSERT INTO #Status VALUES(314, 'StatusE', 1)INSERT INTO #Status VALUES(15, 'StatusF', 1)INSERT INTO #Status VALUES(22, 'StatusG', 1)INSERT INTO #Status VALUES(300, 'StatusX', 2)INSERT INTO #Status VALUES(310, 'StatusY', 2)INSERT INTO #Status VALUES(320, 'StatusZ', 2)INSERT INTO #RegStatus VALUES('7A6058D0-06CB-4E83-A8C4-B1AFC74B11F0',200, GETDATE())INSERT INTO #RegStatus VALUES('7A6058D0-06CB-4E83-A8C4-B1AFC74B11F0',210, GETDATE())INSERT INTO #RegStatus VALUES('7A6058D0-06CB-4E83-A8C4-B1AFC74B11F0',115, GETDATE())INSERT INTO #RegStatus VALUES('8B94A666-A3DD-4CB1-89A0-9910047AE7A0',112, GETDATE())INSERT INTO #RegStatus VALUES('8B94A666-A3DD-4CB1-89A0-9910047AE7A0',314, GETDATE())INSERT INTO #RegStatus VALUES('8B94A666-A3DD-4CB1-89A0-9910047AE7A0',200, GETDATE())INSERT INTO #RegStatus VALUES('8B94A666-A3DD-4CB1-89A0-9910047AE7A0',22, GETDATE())INSERT INTO #RegStatus VALUES('58AF0FC6-C900-4BD0-B3F7-F9D62701F021',15, GETDATE())INSERT INTO #RegStatus VALUES('58AF0FC6-C900-4BD0-B3F7-F9D62701F021',115, GETDATE())INSERT INTO #RegStatus VALUES('58AF0FC6-C900-4BD0-B3F7-F9D62701F021',200, GETDATE())INSERT INTO #RegStatus VALUES('58AF0FC6-C900-4BD0-B3F7-F9D62701F021',115, GETDATE())SET NOCOUNT Off/*This is a query from within a function that I use to not only get thelateststatus for one registrant, but I can use it to get the latest statusfor everyone as well.*/DECLARE @RegStatusCatID int,@RegID UNIQUEIDENTIFIERSET @RegStatusCatID = 1SET @RegID = nullselect LS.*, S.StatusName, S.StatusCategoryIDfrom #Status Sjoin(select RS.RegistrationID, RS.StatusID, RS.StatusTimeStampfrom #RegStatus RSjoin(SELECT RS.RegistrationID , max(RS.UniqueRowID) UniqueRowIDFROM #RegStatus RSjoin #Status Son RS.StatusID = S.StatusIDand S.StatusCategoryID = @RegStatusCatIDand (@RegID is nullor (@RegID is not nulland RS.RegistrationID = @RegID))group by RS.RegistrationID)LSon RS.UniqueRowID = LS.UniqueRowID) LSon S.StatusID = LS.StatusID--SELECT * FROM #RegStatusDROP TABLE #RegStatusDROP TABLE #Status
View 4 Replies
View Related
Aug 2, 2002
Does anyone know how I can get last day of month
if I pass a function a given month and and given year.
@Month = 2
@Year = 2004
The result I would need is 29 because there are 29 in
the month of February in the 2004.
Any help on this is greatly appreciated.
Kellie
View 1 Replies
View Related
Apr 22, 2015
following table global_usage
ID varchar (contains alphanumeric values,not unique)
Territory (combined with ID unique)
Total_Used int can be null
Date_ date (date of the import of the data)
ID Territory Total_Used Date_
ACASC CAL071287 2014-06-01
ACASC CAL071287 2014-08-01
ACASC CAL071288 2014-09-01
[Code] .....
Now the problem,per month I need the most recent value so I'm expecting
ACASC CAL071287 2014-06-01
ACASC CAL071287 2014-08-01
ACASC CAL071288 2014-09-01
ACASC CAL071288 2014-11-01
ACASC CAL071190 2014-12-14
ACASC CAL071286 2015-01-22
ACASC CAL071165 2015-02-01
ACASC CAL071164 2015-03-01
I've tried a few thing like group,having even row_number() but I keep getting wrong results
View 6 Replies
View Related
Apr 30, 2007
Hi every one,
I have a database table and currently users may retrieve records for a specified date range by providing the start and end dates and then records between those dates provided are retrieved. For example if users wanted to view all records entered in april, they would have to select 04/01/2007 as the start date and then 04/30/2007 as the end date. The records for april would then be displayed in a gridview.
How can configure my sql query such that instead the user selectes a month from a dropdownlist of 12 months. I would love a user to just select the desired month from a list instead of selecting start and end dates. Eg if they are intrested in a report for june, then they should just select june from the list instead of specifying the start and stop dates. HOW can i achieve this.
View 4 Replies
View Related
Jan 17, 2014
I'm trying to find the most succinct way to get the last occurrence of April 1st given a date.
At the moment I'm using this:
DECLARE @Date DATE = '20131217'
SELECT CONVERT(DATE, CAST(DATEPART(YEAR,
IIF(
--If we're at the start of a year
--we'll need to go back a year
DATEPART(MONTH, @Date) IN (1,2,3),
DATEADD(YEAR, - 1, @Date),
@Date
)) AS VARCHAR(4)) + '0401')
View 8 Replies
View Related
Mar 31, 2008
i have to input month/year can u tell me what would the datatype of that column? - should it be datetime or just month/year? what would be the datatype?
i have to make function called getQuantityByMonth that when given the following inputs:
input: campaign,begin month/year, end month/year
returns the item sales for the items in a campaign with the following column headers...
output: period, periodint, campaign, itemnmbr, totalquantity
@startmonthyear datetime
@endmonthyear datetime
This is hardcoded, but the output of this is an example of what i would want. The purpose of this is to be able to do a multi-line graph.
select 'Oct 07' as Period, 200710 as PeriodInt, campaign,itemnmbr, totalquantity from
mycampaignitemquantity('COPD','10/1/2007','10/31/2007')
union
select 'Nov 07' as Period, 200711 as PeriodInt, campaign,itemnmbr, totalquantity from
mycampaignitemquantity('COPD','11/1/2007','11/30/2007')
union
select 'Dec 07' as Period, 200712 as PeriodInt, campaign,itemnmbr, totalquantity from
mycampaignitemquantity('COPD','12/1/2007','12/31/2007')
union
select 'Jan 08' as Period, 200801 as PeriodInt, campaign,itemnmbr, totalquantity from
mycampaignitemquantity('COPD','1/1/2007','1/31/2007')
union
select 'Feb 08' as Period, 200802 as PeriodInt, campaign,itemnmbr, totalquantity from
mycampaignitemquantity('COPD','2/1/2007','2/28/2007')
union
select 'Mar 08' as Period, 200903 as PeriodInt, campaign,itemnmbr, totalquantity from
mycampaignitemquantity('COPD','3/1/2007','3/31/2007')
order by itemnmbr, periodint
thanks for the help.
View 15 Replies
View Related
Dec 19, 2007
hi! i have this following query:Select DATEADD(YEAR, -2, @sDate),(dateadd(dd,-(day(dateadd(yy,1,@sDate))),dateadd(yy,1,@sDate)))..the results of these are:2005-01-01 ,2007-12-31 but i want 2007-12-31 to be 2005-12-31..how can i do that using dateadd function?
Funnyfrog
View 5 Replies
View Related
Jul 30, 2015
I want to get the latest comment for each id based on the maximum createdDate and not sure how to do this, tried to do Max but it was still returning all the rows.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Audit](
[id] [nvarchar](64) NOT NULL,
[Code] ....
View 2 Replies
View Related
Oct 24, 2007
Hi,The problem here in hand is comparing the month & year ranges rather than the entire date. I am passing a start month and start year along with the end month and end year, now the query that i have written does not seem to be appropriateMy Query:MONTH(Date_Added) BETWEEN @StartMonth AND @EndMonthAND YEAR(Date_Added) BETWEEN @StartYear AND @EndYearFor some reason this works fine if i specify the startmonth as 1 and endmonth as 12, whereas if i specify 1 and 1 it doesnot work. Can anyone help me by refining my query so that i can search a particular date within mm/yyyy and mm/yyyy. Thanks in advance.Santosh
View 5 Replies
View Related
Jan 9, 2006
hi
I tried below but it doesnt work
select date_field from tbl group by DAY(date_field)
View 1 Replies
View Related
Jun 2, 2008
hai freinds ,
This is the query iam using to retrieve year and its month from a datetime column
quote:Select Distinct DateName(mm, col_datetime) as 'Month',
year(col_datetime)
as 'Year'from table_name
Order By DateName(mm, col_datetime)
result for the above query is
quote:
month year
june 2008
june 2007
july 2007
july 2008
aug 2007
aug 2008 and so on.....
but my need is
quote:
month year
june 2008
july 2008
aug 2008
june 2007
july 2007
aug 2007
and so on.....
so can someone fix it or give me a idea
thanks friends
View 3 Replies
View Related
Dec 17, 2007
Hi i have a where clause which i think i need to change
i currently have the code below but dont think it right
i think it needs to be (O_Date) between @month1 @year AND @month2 @year2, but not sure how this should be done?
WHERE MONTH(O_Date) Between @month1 AND @month2
and YEAR(OW.O_Date) Between @year AND @year2
View 7 Replies
View Related
Jan 19, 2008
My data is mainly updated each month. Most of my tables have a month and year column. I have many statements such as this when I need to join tables:
SELECT equity FROM vMonthlyFirmSummary WHERE MonthlyInputs.year = vMonthlyFirmSummary.year AND MonthlyInputs.month = vMonthlyFirmSummary.month
Is this bad database technique? Do you think instead I should try to create a string key field such as 2007-01 (Year - Month)? Please give any insight on how to make the DB simpler. Thanks.
View 3 Replies
View Related
Mar 8, 2008
Hi,
I need to see if a record has been inserted into a table, and the condition is if the record has been inserted for the current year and month and day, if not, I can insert a new row.
SO I need to do:
IF NOT EXISTS (SELECT * FROM myTable WHERE Created = @Created)
But it has to be comparing the year,month and day (excluding the time part of the datetime type).
View 9 Replies
View Related
Jul 23, 2005
Hi,We are using Month-year tables to keep the history of long transactionof our application. For example:We capture the details of a certain action in table"TransDtls<CurrMonth><CurrYear>" (this month: TransDtls072005).This way tables keep growing. every month a new table gets created. Wehave done it because we estimated that every month year table willcarry around 2 - 3 Lac records and most of the time the operations willwork on current month year table.Avoiding this way and carrying on with single table instead of "Monthyear" table might lead us system performance issues.But now we are a bit confused on the way we are heading and also facingthe implementation issues like manipulating data from different"month-year" tables. Could anyone please help us to make our visionclear on this?Looking for your valuable comments.Thanks.
View 8 Replies
View Related
Jan 20, 2006
I am trying to return the latest date in a stored procedure as shown below, but get the error 'incorrect syntax near @strLastDate'
CREATE PROCEDURE spRB_GetLastDateBookingDates
@strLastDate datetime OUTPUT
AS
SELECT max(BD_DateRequired) as @strLastDate
FROM tblRB_BookingDates
GO
RETURN
View 8 Replies
View Related
Jan 15, 2007
Tried this: SELECT CONVERT(varchar,fieldMonthYear,107) 'Month in Question' FROM .....That returns: Apr 01, 2006What I need is this: April 2006 or even Apr 2006. But no date for the day.Is there a way I can trim the center 4 characters of this now converted varchar? This is in a datalist, btw. Thanks!bs.
View 3 Replies
View Related
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