.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

sql query for month and year of date

Posted By:      Posted Date: October 21, 2010    Points: 0   Category :Sql Server
I have a table with smallint columns for day,month,year. Now I want to select data lets say for month 10,year 2009 to month 2,year 2010. Can anyone help me in writing this query?

View Complete Post

More Related Resource Links

Date format for Year, Year-Month, and Date (Year-Month-Day) where input is not known

I have a requirement to capture historical events in a table. Now some events will have only Year, some Year/Month, and remaining where Date is known. We should be able to store them in the column and be able to sort etc. When publishing the information, we should be able to publish as was the input, Year only, Year-Month only, or Date. I looked at the newer Date data type. I can insert a 4 digit year, but on retrieving it is YYYY-01-01. I do not know if it has input YYYY or YYYY-MM-DD and is indeed a Date or a Year. I am trying to avoid saving the format information in another column or something. For sorting, when records have same Year, I would have another column to do relative sorting... So question is - what are my best options with SQL/Entity Framework combo. And what others have done, when encountering similar - if any. Thanks in advance. --Sharad 

Display the Sum of hours and Month Year using sql Query

Hi,  I have,hours(in varchar),Id in table tbl_x ,i need the sum of hours, monthyear(eg. mar 2010)for the last three months.But with two separate queries i am getting these results.but actually i need in the following format   Month/Year      TotalHours-----------------    ----------------Mar 2010            0400Apr 2010             0450-----------------------------------to get month/Year i am using this querySELECT right(convert(varchar, fromdate, 106), 8) from tbl_x where id='11101' for the sum of hours SELECT SUM(CAST(hours AS INT))AS TOTALHRS FROM tbl_x WHERE id='11101'

Query acting weird.. larger date range works in 1min 26sec and a smaller range say 1 month - 3 month


I have no clue why my query is acting weird

If i try to run it for 1/1/2010 9/30/2010 the query takes around 1min 26 sec and  return around a million rows

and If i run for 8/1/2010 to 8/31/2010 it takes forever to it...

basically i am getting data from 5 tables and putting it in a temp table and then updating that temp table 2-3 times with some information and then displaying it.

I am stumped as to why it works fast for a longer date range and runs the  snail for a small period of time..

I am in the verge of pulling my hair and going crazy..

any help will be appreciated.




Ignore date and consider month and year to match


Hi there,

It is required to retrieve the records where ONLY Start Month, Year AND End Month, Year are passed. Trying below SQL to get these with no success. 

registrationdate BETWEEN(MONTH((registrationdate) = 01) AND (Year(registrationdate)= 2009)) AND ((Month(registrationdate) =03) AND (Year(registrationdate)=2010))


Help is appreciated.

Time Dimension for YTD using assigned Month and Year integers without Date datatype


Hi, most time dimensions are setup using a base Date field in the fact table, and they have plenty of issues for time analysis as it is. However my fact sales records have the time aspect assigned by pre-calculated periods, because depending on various factors, monthly final invoices are all raised on varying days (usually 2nd friday of month but can change). The monthly period is therefore not a straight calendar month. Probably a very common scenario.

So, the invoicing system already assigns the year (ie 2009, 2010, 2011) and monthly period (1, 2, 3 ... 12 with 3 representing march, even though that might represent 13th march to 9th april) and I want to use those as Time dim so we can do YTD, growth-on-prev-year etc.

It looks like its best to setup 2 Dimensions to link to 2 DataColumns/Attributes in the Fact table (say, FYear and FMonth, both integers). That way I can assigned attribute names like March to key column 3. If I combined them into 1 dimension with both fields making up a single key column, would have to either repeat the month names or link it to another Star schema I believe.

I can use the Add Business Intelligence wizard to make the Dimensions into Time ones instead of regular but I'm still not totally sure if this is the best structure/method and once done, how to use the YTD calcs to show in the cube browser (and my MDX knowle

query - generate month, year (count) for blog archive


hi guys.

from my sql blogs table, I want to generate blog archive section on my master page. like;

january, 2010 (20)

fabruary, 2010 (35)

I cannot come up with a linq to sql query on this. do you have any idea how it can be done ?

Matrix Report With Month/Year Columns - Display date even when there are no records for that month


I've created a matrix report that displays the quantity of different products  set to expire by month/year. The stored procedure returns records for a variety of products and each record contains an expiration date. If there are no products/records that contain an expiration date of lets say 6/2010 then 6/2010 will not appear as a column in the report.

I need a way to force these month/year columns to appear in the report.


Does anyone have a suggestion on how I can make that happen?


Rick Dowdall


Crawler fails to register date properties of user profiles with the month of January, April, August


This seems to be a bug when the crawler search the user profiles in MOSS 2007.  When crawled, user profiles with a SPS-HireDate in the months of January, April, August and December will be detected, but a full-text (SQL) search returns those profiles without the HireDate field.

User profiles with HireDates in other months work correctly, returning the HireDate in the search.  And changing the month of a problematic user profile also fixes the problem.

This problem is also reflected in the fact that while we have 499 user profiles using the SPS-HireDate property,  the managed property page from the search section only has 350 items with the HireDate property.

We're running MOSS 2007 32bit with SP2 with an English language base and the Spanish language pack. I'd considered date format problems, but I can't imagine how some months would work, while others wouldn't.

Any ideas?

Need help in Date Query

HI Guys I have date like 2008-10-31 16:36:567 I want to convert like 20081031 00:00:000 for this I'm using convert(datetime,(convert(varchar(8),replace('2008-10-31 16:36:567','-','')))) is there any option to do this?

How to create a calcuated member, which will always return the date one month before the currentmemb

I need to create a calculated member in the cube script, which will be subsequently used in various other script calculations.  It needs to return the date, which is 1 month before the currentmember of the Date dimension. I tried something like this: CREATE MEMBER CURRENTCUBE.[Measures].[LastPD]   AS           PARALLELPERIOD([Date].[Calendar].[Month], 1, [Date].[Calendar].currentMember) ,VISIBLE = 1; However when I then try to check the values with this query: SELECT [Measures].[LastPD] on 0, [Date].[Calendar].[Date].members on 1 FROM [TravCSAT] ; I only get NULLs for [LastPD].  Any idea what I am doing wrong?

How I select Start of week is Friday from date of Year ?

Hello everyone, I am tring to solve How i select Start date is Friday from week? Details for which i want to show I have dtmDate column in a query. from that date i display week of that date as per using (ww,dtmDate) as dtmWeek, and parameters are StartDate & EndDate Suppose I select StartDate as 1/1/2007 & End Date as 12/31/2007   I  do not want to show Output as: Weeks                      Column1          Column2 1/1/2007 (Thuesday)       5                     6 1/2/2007 (Wed)               4                     2 | | 1/5/2007  (Friday)            1                      8 1/6/2007 (Saturday)        7                     

Need to convert query string(date - 09/15/2010) to a text format - yyyymmdd

I am fairly new to C # and need some assistance with a form page.  I have created a simple form that requires the user to select a beginning date and ending date.  I then pass the values to my code behind page via query strings.  I have them passing, but I need the format to be change to a different format.  Unfortunately the database does not use the standard date format.  It requires the date to be in a text format as YYYYMMDD.Form: <tr> <td> Beginning Date:</td> <td><asp:TextBox runat="server" ID="begDate"></asp:TextBox> <asp:Image ID="Image2" ImageUrl="~/images/calendar_schedulehs.png" runat="server" /></td> </tr> Code Behind: protected void createReport_Click(object sender, EventArgs e) { StringBuilder url = new StringBuilder("Report/TopCustomer.aspx?"); url.Append("BegDate=" + begDate.Text); url.Append("&EndDate=" + endDate.Text); url.Append("&Brnch=" + ddlLocation.SelectedValue); Response.Redirect(url.ToString()); Current URL: TopCustomer.aspx?BegDate=09/15/2010&EndDate=09/30/2010&Brnch=300I need to have the above URL change to:TopCustomer.aspx?BegDate=20100915&E

report expression for month and year

Hi , Can anyone help me how to write a report expression to get the following out put? Actually this value is the month of previous month. I want to set default month name of the parameter to previous month. This is sep.So it should display like this; Aug - 10 Thanks shamen

Retrieve month name and last 2 digit of yr from date column

Table contain one column [d_matur] [datetime] NULL 2014-06-20 00:00:00.000 2015-03-20 00:00:00.000 like this now I want to retrieve month name like June as well as last two digit of year like 14 if anyone know query how to get these from above column please let me know.Thanks

parameterized query and Date Field

Hi!Using this SQL:SELECT fac_op_d.cod_art_i, SUM(fac_op_d.cantidad) AS total, inv_mp_m.nombre, fac_op_d.fec_doc FROM fac_op_d, inv_mp_m WHERE fac_op_d.cod_art_i = inv_mp_m.cod_art_i AND (fac_op_d.cod_art_i LIKE ? + '%') AND (inv_mp_m.almacen = 1) AND (fac_op_d.fec_doc BETWEEN ? AND ?) GROUP BY fac_op_d.cod_art_i, inv_mp_m.nombre, fac_op_d.fec_docThis is a query to an old FoxPro database on a server (Same Network). This work in the execution, but just passing the date values as aaaa/mm/dd.On my page when a pass two DateTime Parameters from two TextBox it throw "Unable to recognize the string as a valid DateTime Value"I'm using Ajax Calendar exterder on the textbox to be more specific.Here, (My Country)  the format i'm using es dd/mm/aaaaAnd when i select the datepicker it comes in this format, and then a get the DateTime error type.I can get the rows in the query builder just passing the date like "2010/01/15" and "2010/01/30" for example.Hay can i force the texbox to get this format aaaa/mm/dd?regards

T-SQL query, average of daily time periods over a date range



I'm building a report in Crystal Reports using a SQL command against a T-SQL 2005 telephony database.

I need to be able to run the query across a given datetime range, 6 months for example and bring back a 5 day display (Mon-Fri) with a group for every 15 minute interval in each day.

The group figures need to contain an average of the amount of calls presented for each 15 minute interval on any day across the whole datetime range, so for example the Monday 10:00 - 10:15 figure would be an average of all calls presented in every 10:00-10:15 range on each of the Mondays that fall within the datetime range.

I've got a query built now that gives total presented figures grouped by these intervals across one week but I can't figure out how to do this average function across a range.

Does anyone have any idea how I'd go about accomplishing this? I'm pretty new to SQL but keen to learn so any pointers on functions to research etc would be very much appreciated.

Thanks alot in advance, Andy.

Query for detail view across one week included below for table/fields etc...



count(DISTINCT Calls.SessionID) as Presented, min(Calls.startDateTime) as DateTime

INNER JOIN QueueDetail
ON Calls.sessionID =  Queues.sessionID
AND Calls.sessionSeqNum =  QueueDet

first date of previous month?

How to get the first date of previous month?
PS.Shakeer Hussain Hyderabad
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend