Showing posts sorted by date for query last day. Sort by relevance Show all posts
Showing posts sorted by date for query last day. Sort by relevance Show all posts

Date Functions – SQL Server vs MySQL

Continuing my series on how same things can be done differently in SQL Server and MySQL, in this post, we will see some Date Functions in SQL Server and MySQL. I have put them in a table format so that it becomes easier for you to follow:
 
SNo Purpose SQL Server MySQL
1 Find out current date and time Getdate() now()
2 Find out day name of current date datename(weekday ,getdate()) Dayname(now())
3 Find out day of month datename(day,getdate()) dayofmonth(now())
4 Find out day of week datepart(weekday,getdate()) dayofweek(now())
5 Find out day of year datepart(weekday,getdate()) dayofyear(now())
6 Find out year value year(getdate()) year(now())
7 Find out month value month(getdate()) month(now())
8 Find out day value day(getdate()) day(now())
9 Find out last day of month eomonth(getdate()) last_day(now())
10 Find out month name datename(month,getdate()) monthname(now())
11 Find out Time value from seconds cast(dateadd(second,seconds_value,0) as time) sec_to_time(seconds_value)
12 Subtract days from date dateadd(day,-day_value,getdate()) date_sub(now(), interval day_value day)
13 Add days to date dateadd(day,day_value,getdate()) adddate(now(), interval day_value day)
13 Get UTCDATE GETUTCDATE () UTC_TIMESTAMP()
14 Format a date (dd-mm-yyyy) format(getdate(),'d-MM-yyyy') DATE_FORMAT(now(), '%d-%c-%Y');

SQL Server 2012 - Effective usage of EOMONTH function‏

Continuing my series on SQL Server 2012, today we will explore a new function in SQL Server 2012 called EOMONTH (End of Month) which can be used to find the last day of the month. In earlier versions, we have to use date functions like dateadd, datediff, etc to find out the last day of the month.

Consider this example for versions prior to SQL Server 2012

declare @date datetime;
set @date = '20120223';
select dateadd(month,datediff(month,-1, @date),-1) as last_day;

The result is 2012-02-29 00:00:00.000

The same can be achieved using EOMONTH function in 2012


declare @date datetime;
set @date = '20120223';
select eomonth ( @date) as last_day;

The result is 2012-02-29

This function can be used in various purposes, like finding last day of next month

declare @date datetime;
set @date = '20120223';
select eomonth ( @date,1) as last_day;

The above results to 2012-03-31. The additional parameter is added as a month and last day is decided.

We can also make use this function to find out first day of month

declare @date datetime;
set @date = '20120223';
select dateadd(day,1,eomonth ( @date,-1)) as first_day;

The EOMONTH finds the last day of previous month and adding one day to its results, fetches the first day of the month.

This way we can effectively make use EOMONTH function for various purposes.

Most Popular SQL Server Articles in 2011

With 2012 fast approaching and 2011 drawing to an end, we've put together our list of the Most Popular SQL Server articles on SQLServerCurry.com this year.

I would like to thank each one of you who has visited my blog or contributed to it by submitting a Guest post, Subscribing to RSS Feed, by joining me on Twitter, retweeting posts or promoting the articles and giving regular feedbacks via rating, comments or Emails. A special note of thanks to Madhivannan and Pravin Kumar for their contributions.

Here are some articles that were liked the most by readers like you. Have a very Happy New Year 2012!

SQL Server Administration Articles


T-SQL Articles

T-SQL, SQL Administration Articles Link List – August 2011

Here’s a quick wrap up of the articles published on SQLServerCurry.com in the month of August 2011

SQL Server Administration Articles

Every .NET Developer Should Know About the Database they are working with - I am a strong believer that a Developer should understand the databases and network he/she is interacting with. As a .NET Developer, having TSQL and SQL Server Administration knowledge to some degree of depth, really helps to design and develop your applications as well as communicate with the DBAs and admins you work with. In this article, I have attempted to list some articles we have written in the past that will give you information about handling a SQL Server 2005/2008 database.

SQL Server: Last BackUp Date - A database developer recently asked me a simple way to find the last backup date of a database. He was using SQL Server 2005. I had written a similar query for the MSDN wiki and here’s the same for my blog readers

SQL Server Connector for Apache Hadoop - Microsoft has released a new tool/connector based on SQOOP for those looking out to transfer data between SQL Server 2008 R2 and Apache Hadoop

SQL Server: Move Data to a Different Table using OUTPUT clause - Suppose you want to move some data from one table to another table and then delete the data from source table.

T-SQL Articles

SQL Server: Retreive all records between Two Rows of a Table without a Numeric Primary Key - Let us quickly see how to fetch all the records between two rows in a SQL Server table which does not have a numeric primary key.

Compound Assignment Operators in SQL Server 2008 - Compound assignment operators are newly introduced in SQL Server 2008 and the code certainly looks cleaner and easier to type while using them. I am surprised why weren’t they introduced in earlier SQL Server versions at the first place, however now that they are here, let’s quickly learn how to use them

SQL Server: Last Day Previous Month without DATEADD and DATEDIFF - Suppose you want to find the last day of the previous month, you can always use this method

SQL Server: Limit Millisecond Part in DateTime2 Datatype - Till version 2005, SQL Server supported only the datetime datatype which stored date and time with milliseconds upto three digits. However SQL Server 2008 supports separate data types DATE and TIME as well DATETIME2 datatype which stores milliseconds upto 7 digits.

SQL Server: Handle Nulls While Sorting Data in Ascending Order - The SQL Server ORDER BY Clause is used to order the result sets by a set of columns. If you use ORDER BY col ASC, NULL values come first, if you do ORDER BY col DESC, NULL values are shown last, but remaining values are ordered in descending order.However what if you want order the result sets by a particular column in ascending order and also keep all NULL values in last rows?

Other SQL Articles

LocalDB Denali: New version of SQL Express - Microsoft released LocalDB a couple of weeks ago as part of SQL Denali CTP 3. LocalDB or Local Database Runtime is the new version of SQL Express created specifically for developers

SQL Server Denali CTP 3 Goodies - Microsoft recently released the SQL Server Denali CTP 3 Product Guide which contains plenty of goodies to help you learn and get up and running before Denali hits the shelves

SQL Server Migration Assistant for Denali CTP3 - if you have a requirement of migrating from your Ms Access database to all higher editions of SQL Server, then here’s some news for you. The SQL Server Migration assistant for Access now supports Denali CTP 3 too

SQL Server: Last Day Previous Month without DATEADD and DATEDIFF

Suppose you want to find the last day of the previous month, you can always use this method:

select dateadd(month,datediff(month,0,getdate()),0)-1

The above code finds the month difference between 1900-01-01 and current date and adds it to same date, so the result is first day of the month. Adding -1 to this result returns the last day of previous month. This is a very common approach where we use the DATEADD and DATEDIFF functions.

There is another method of finding the Last day of previous month where we will not use the dateadd and datediff functions. Here it goes:

select cast(getdate()-day(getdate()) as date)

The code shown above subtracts DAY from GETDATE(),  so it returns last day of previous month.

Casting it to the DATE data type gives only the date.

OUTPUT
Last Day Previous Month

SQL Server: Check if Date is End of Month

Here’s a very simple query that checks if the date is End of the Month.

DECLARE @Dt DATETIME 

SET @Dt = '2011-06-30'

IF MONTH(@Dt) != MONTH(DATEADD(DAY,1,@Dt))
BEGIN
PRINT 'End Of Month'
END

As you can see, we are using MONTH(DATEADD(DAY,1,@Dt)) which if run for the June date returns 7 if we are the end of the month. For any other June date, it will return 6. All we are doing is comparing it with MONTH(@Dt) to see if the two values match. If it does not, it is the end of the month.

OUTPUT

image

SQLServerCurry.com author Madhivanan has suggested an alternate method to check if the given date is the last date of the month. Here it is:

DECLARE @Dt DATETIME
SET @Dt = '2011-06-30'
IF DAY(@Dt+1) = 1
BEGIN
PRINT 'End Of Month'
END
ELSE
BEGIN
PRINT 'Not End Of Month'
END


The code DAY(@Dt+1) adds 1 day to the given date. If the given date is last day of month,
the date becomes first day of next month so the DAY function will return 1. Otherwise it is
not the last day of month.

Update: Brad Schulz made a good point on this alternate method. He says "It will not work with the SQL2008 date datatype. You can not add an integer to a date datatype like you could with datetimes. So instead of DAY(@Dt+1) it is best to do DAY(DATEADD(day,1,@Dt)), which will work in all versions." Thanks Brad!

SQL Server Tutorials on Date Time

One of the most frequently asked question by SQL developers, is on handing Date,  Time and other related datetime values in SQL Server. Developers are always looking out for solutions which demand either converting Date Time Values or finding date time ranges and so on. Madhivanan and I have already written a couple of articles on handling DateTime in SQL Server. In this post I will share some of the links with you.

Hope you find them useful. If you do, make sure you retweet and let the other devs know about this link list.

FLOOR a DateTime in SQL Server

SQL Server: Insert Date and Time in Separate Columns

SQL Server: Group By Days and Create Categories

SQL Server: Insert Date and Time in Separate Columns

SQL Server: Group By Year, Month and Day

SQL Server: First and Last Sunday of Each Month

SQL Server: First Day of Previous Month

SQL Server: Convert to DateTime from other Datatypes

Date Difference in SQL Server in Days, Hours, Minutes and Seconds

Display Dates in a Particular Format in SQL Server

Truncate Hour, Minute, Second and MilliSecond in SQL Server

Calculate Interest on an Amount Between two Dates using SQL Server

Working with Different Time Zones in SQL Server 2008

Print Dates without Day or Time in SQL Server

Calculate Age from Date Of Birth using SQL Server

Replace SQL Server DateTime records of a column with UTC time

Calculate Average Time Interval in SQL Server

List all the Weekends of the Current Year using SQL Server

Create Date Ranges for Consecutive dates in a SQL Server Table

SQL Query to find out who attended office on Saturday

Convert Date to String in SQL Server

Convert Character string ISO date to DateTime and vice-versa

Select dates within the Current Week using SQL Server

Generate a Start and End Date Range using T-SQL

Convert From EST to GMT Time and vice versa in SQL Server

Convert DateTime to VarChar in SQL Server

How to Display DateTime Formats in Different Languages using SQL Server

Finding the Business Days In a Quarter and Number them in SQL Server 2005/2008

Find the WeekEnds in this Quarter or Year using SQL Server 2005/2008

Comparing Dates In Two Columns using SQL Server\

Some Common DateTime Formats in SQL Server 2005/2008

First weekday of a month in SQL Server

DATENAME() function in SQL Server 2005

Return date without time using Sql 2005

T-SQL, SQL Administration and SSRS Articles Link List – April 2011

Here’s a quick wrap up of the articles published on SQLServerCurry.com in the month of April 2011

SQL Server Administration Articles

SQL Server: Disable Table Constraints (all or some) - Constraints let you define a way to automatically enforce the integrity of a database. A table constraint is declared independently from a column and can be applied to more than one column in a table. Sometimes you may need to disable one or all table constraints, in order to import data, truncate tables etc.

Transfer Logins from SQL Server 2005 to SQL Server 2008 - When you want to move a database from one server to another, you can take a backup of the database and restore into the other server. However this will not transfers the logins from one SQL server to another, say SQL Server 2005 to SQL Server 2008.

SQL Server: Monitor Long SQL Agent Jobs - In SQL Server, there are various jobs running on the server, each solving a different purpose. Sometimes these jobs run for a long time. The best way to identify and monitor these long running jobs is to make use of a profiler.

Monitor Running Processes in SQL Server 2005/2008 - You often need to monitor the processes running on the server in order to improve the performance, by tuning them.  A common option is to make use of a profiler. But in SQL Server versions starting 2005, we can also use dynamic management views.

SQL Server: Transfer Objects From One Schema to Another - This post describes how to transfer objects from one schema to another. A simple method is to make use of the ALTER Schema statement as shown below

T-SQL Articles

SQL Server: First and Last Day of Year, Quarter, Month and Week - With so many questions floating around calculating the first and last day of a given duration in SQL Server, here’s a post that explains the technique of calculating the first and last day of a given duration

SQL Server: Increment an AlphaNumeric Number‏ - Your columns may have a categorization scheme in the form of an alphanumeric number. and it may be needed to have a customized incremental value for this scheme. Consider that you want to have numbers in the series like ABC1, ABC2, ABC3  etc. In SQL Server, there can be many methods to do this.

XML Basics in SQL Server 2005 and 2008 - In this article, we will see how to write basic queries to insert, query and generate XML data in SQL Server 2005/2008. For this demonstration, I am using the ‘Northwind’ database.

SQL Server Management Objects 2008 (SMO) New Features - In this article we will practically explore some features of SQL Server Management Objects

SQL Server: String operations in XML document‏ - SQL Server versions starting from 2005 and onwards supports storing and retrieving data as XML format. Using the XML datatype, you can do lot of things such as splitting string, string concatenation etc. In this post, we will see how we can use XML datatype to split strings

SQL Server: Search Similar String in a Table - There are may ways to look for similar strings in a SQL Server column. The most common  method is to make use of LIKE operator. Let us see the different ways to look for similar string in a table.

SQL Server Reporting Services (SSRS) Articles

SQL Server: Designing Key Performance Indicator Report in SSRS 2008 - In this article, we will see how to display ‘Key Performance Indicators’ based on the different conditions in SQL Server Reports. For this demonstration we will use the ‘Northwind’ database

SQL Server: Designing Tablix Report in SSRS 2008 - In this article we will see how to design a Tablix (Table + Matrix) report in SQL Server Reporting Services (SSRS) 2008. For this demonstration, we will use the AdventureWorks sample database provided by Microsoft.

SQL Server: Designing Chart Report in SSRS 2008 - In this article, we will see how to design a Chart report in SQL Server Reporting Services 2008. For this demonstration we will use AdventureWorks sample database provided by Microsoft.

SQL Server: First and Last Day of Year, Quarter, Month and Week

With so many questions floating around calculating the first and last day of a given duration in SQL Server, here’s a post that explains the technique of calculating the first and last day of a given duration. We will cover the following:

- Calculate First and Last Day of the Year
- Calculate First and Last Day of the Quarter
- Calculate First and Last Day of a Month

First and Last Day of Year

SQL First Last Day Year
To get the first day of the year, we are using the DATEDIFF function to determine the number of years from ‘1/1/1900’ to the current date (GETDATE). We then add this calculated number result (in this case 111) to ‘1/1/1900’, to obtain the first day of the year.

Similarly, a simple trick is adopted to get the last day of the year. We get the first date of the ‘next year’ and simply subtract one day from it. So the expression SELECT DATEADD(yy, DATEDIFF(yy,'',GETDATE()) + 1, 0) gets you the first day of the ‘next’ year. Subtracting 1 from it gives you the last day of the current year.
The same approach is adopted to find the last day of the quarter and the month.

First and Last Day of the Quarter

SQL First Last Day Quarter

First and Last Day of a Month

SQL First Last Day Month

Here are all the three queries for you to try out:

-- First and Last Day of Year
SELECT DATEADD(yy, DATEDIFF(yy, 0, GETDATE()),0)
as 'First Day of Year'
SELECT DATEADD(dd, -1, DATEADD(yy, DATEDIFF(yy,0,GETDATE()) + 1, 0)) as 'Last Day of the Year'


-- First and Last Day of Quarter
SELECT DATEADD(qq, DATEDIFF(qq, 0, GETDATE()), 0)
as 'First Day of Quarter'
SELECT DATEADD(dd, -1, DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) + 1, 0))
as 'Last Day of the Quarter'


-- First and Last Day on Month
SELECT DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0)
as 'First Day of Month'
SELECT DATEADD(dd, -1, DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) + 1, 0))
as 'Last Day of Month'


OUTPUT
SQL Server First Last

T-SQL and SQL Server Administration Articles Link List – February 2011

Here’s a quick wrap up of the articles published on http://www.sqlservercurry.com/ in the month of February 2011

SQL Server Administration Articles

Fastest Way to Update Rows in a Large Table in SQL Server - Many a times, you come across a requirement to update a large table in SQL Server that has millions of rows (say more than 5 millions) in it. In this article I will demonstrate a fast way to update rows in a large table

View Object Dependencies in SQL Server 2008 - Viewing object dependencies within a database as well as between databases and servers has become easier in SQL Server 2008. SQL Server 2008 introduces a catalog view (sys.sql_expression_dependencies) and dynamic management functions (sys.dm_sql_referenced_entities & sys.dm_sql_referencing_entities) that can help in dependency tracking.

SQL Server: Count Rows in Tables and its Size - In this post we will see how to count rows in all the tables of a database using SQL Server

T-SQL Articles

Calculate Median in SQL Server - Median is the numeric value that separates higher half of the list from the lower half. Let us see how to calculate Median in SQL Server

Sort Alphanumeric Data in SQL Server - This post shows how to sort alphanumeric data in SQL Server. You need to use a different approach to get an alphanumeric sort.

SQL Server: Return Multiple Values from a Function - A SQL Server function can return a single value or multiple values. To return multiple values, the return type of the the function should be a table.

SQL Server: Store and Retrieve IP Address - We can store IP addresses in SQL Server in a varchar column. However to retrieve IP address for a specific range, we need to split each part and compare it.

SQL Server: Group By Year, Month and Day - I have seen some confusion in developers as how to do a Group by Year, Month or Day, the right way. Well to start, here’s a thumb rule to follow.

SQL Server: First and Last Sunday of Each Month - This post shows you how to find the First and Last Sunday for each month of a given year, in SQL Server

SQL Server: Storing Images and Other BLOB types - In this post, we will see how to store BLOB (Binary Large Objects) such as files or images in SQL Server.

SQL Server: Highest and Lowest Values in a Row - Calculate both the highest and lowest values in a row without using an UNPIVOT operator.

SQL Server: First Day of Previous Month - A user asked me how to find the first day of the previous and next month in SQL Server

SQL Server: Convert to DateTime from other Datatypes - In this post, we will see how to convert data of different datatypes to a DateTime datatype, in SQL Server.

SQL Server: First Day of Previous Month

A user asked me how to find the first day of the previous and next month in SQL Server. It’s quite simple as explained in Itzik’s excellent book Inside Microsoft SQL Server 2008: T-SQL Programming (Pro-Developer).

Here’s the query

first day SQL Server

Here’s the same query to try out:

-- To Get First Day of Previous Month
SELECT DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()) - 1, '19000101')
as [First Day Previous Month];
GO

-- To Get First Day of Next Month
SELECT DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()) + 1, '19000101')
as [First Day Next Month];
GO

To understand what we just did, first execute the following query:

SELECT DATEDIFF(MONTH, '19000101', GETDATE())

This query returns 1333 (as of this writing) which is the number of months since 1/1/1900. Since we want to calculate a day of the previous month, subtract 1. To calculate a day of the next month, add 1. That’s it, now use the DATEADD function to return a specified date with the number interval (1333) subtracted or added to the datepart (month) of 1/1/1900.

OUTPUT

SQL Server first day output

You may also want to check

SQL Server: First and Last Sunday of Each Month

Find First and Last Day of the Current Quarter in SQL Server

SQL Server: First and Last Sunday of Each Month

This post shows you how to find the First and Last Sunday for each month of a given year, in SQL Server. Let us see the t-sql code first

First Last Day SQL Server

Here’s the same code for you to try out:

declare @year int
set @year =2011

-- First and Last Sunday by SqlServerCurry.com
select min(dates) as first_sunday,max(dates) as last_sunday from
(
select dateadd(day,number-1,DATEADD(year,@year-1900,0))
as dates from master..spt_values
where type='p' and number between 1 and
DATEDIFF(day,DATEADD(year,@year-1900,0),DATEADD(year,@year-1900+1,0))
) as t
where DATENAME(weekday,dates)='sunday'
group by DATEADD(month,datediff(month,0,dates),0)

For this example, we are using the table master..spt_values which is a system table and contains a number column that has numbers from 0 to 2047. We can make this as a number table. Alternatively you can also create a large number table and use it in the query.

Based on the the year value given (in our case 2011), the first day of that year should be calculated. The code DATEADD(year,@year-1900,0) will give us the First day of the year @year.

We need to consider all the date values from January 1st of that year to December 31st.
The where condition number between 1 and DATEDIFF(day,DATEADD(year,@year-1900,0),DATEADD(year,@year-1900+1,0)) makes sure that all date values for that year are considered.

We then find whether the date is a Sunday by using DATENAME function. As we need the first and last Sunday for each month, we need to group the result by each month. The code DATEADD(month,datediff(month,0,dates),0) used in group by clause, groups the
result by each month.

OUTPUT

First Last Day SQL Server

First Sunday of Every Month in SQL Server

I have often seen questions about finding the First Sunday or Monday of every month in SQL Server. Here’s a query that lists the first Sunday of every month in a given duration

Note: You can also check List all the Weekends of the Current Year using SQL Server and First weekday of a month in SQL Server

DECLARE @dow int,
@StartDate DATETIME,
@EndDate DATETIME
SELECT @dow = 1, -- Sunday
@StartDate = '01 Jan 2010',
@EndDate = '31 Dec 2011'

-- Populate CTE with the 1st date of every month
;WITH CTE(mth) AS (
SELECT @StartDate mth UNION ALL
SELECT DATEADD(month,1,mth) FROM CTE
WHERE DATEADD(month,1,mth) <= @EndDate
)

-- SQLServerCurry.com Query to List First Sunday of all Months
SELECT DATEADD(DAY, @dow +
CASE WHEN DATEPART(dw,mth) > @dow THEN 7
ELSE 0
END
- DATEPART(dw, mth), mth) as 'First Sunday'
FROM CTE

OUTPUT

image

Update: Here's a better query SQL Server: First and Last Sunday of Each Month

List all the Weekends of the Current Year using SQL Server

Sometime back, I had posted to Find the WeekEnds in this Quarter or Year using SQL Server 2005/2008. An anonymous user wrote back asking if there was a way to determine the first and last day of the current year and rewrite the same query. Well here it is:

DECLARE @StrtDate datetime
DECLARE
@EndDate datetime
SELECT
@StrtDate = DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)
SELECT @EndDate = DATEADD(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate() )+1, 0))

;
WITH CTE (weekends)
AS
(
SELECT @StrtDate
UNION ALL
SELECT DATEADD(d,1,weekends)
FROM CTE
WHERE weekends < @EndDate
)
SELECT weekends from CTE
WHERE DATENAME(dw,weekends)
In (
'Saturday', 'Sunday')

OUTPUT

image

Exploring Business Intelligence with SQL Server

In this post, we will take an overview of Business Intelligence (BI). We will begin by describing the general term BI and then go towards details of implementation of BI using Microsoft BI platform.

Every organization is always in the process of increasing its revenue. No organization says that we have done some amount of business last year and henceforth we will continue with the same every year. In order to increase the business, the organization has to decide what will be the business growth for the next year and also for further 5 years and so on. The owner of the organization or the Board of Directors can not take a figure out of blue and say that it is the target for the next year. In order to arrive at some number the management has to take into consideration various aspects like the current industry situation, the company’s niche area, weakness and strengths of the company and competitors etc. If the organization is in the business for last 10 years and each year the growth is 10 % then this also becomes the deciding factor. For knowing all the above factors we need to keep the data and utilize it as and when required. Business Intelligence tools help in storing the data, analyzing the data and utilizing it for reports. Business Intelligence can be useful for any size of organization.

Let us take a particular example. Suppose there is a company in production business. They are coming up with a very good product which will provide large profits for them. The organization knows the cyclic trend when the products are launched till the time the sale increases. This trend can be available from previous product launches. The company may take certain decisions based on market survey over the years which suggests the perfect season when the prospective clients may have some funds to spend.

Let us take another example. Let us say we have a company which is in training business. The company deals with all computer related trainings mainly with 2 flavors. First one is where the clients / customers are trained in company’s premises. This type of business is called retail business. Other type of business is where the trainers go to various corporate for delivering trainings. Let us call it Corporate Training Business. Let us focus on how the company will increase the retail business. The company will give advertisements, inserts etc. Suppose the company wants to target a chunk of students who will have a lot of free time once they finish their secondary school or higher secondary school exams. The company approaches various schools, colleges, private institutes and collects the addresses. Thus the data can be gathered by various persons with various means. Some may collect data with a laptop on Access database, some with Excel while some may collect the data on papers. This way the company collects data from various sources. When the exams are approaching they send the students mailers saying “Best wishes for the coming exams and when the exams are over please visit us as we are starting special batches”. Thus a lot of students enquire after the exams and some of them can become actual clients. This was one way of increasing business. This newly gathered data can be combined with the data company is having for previous years. The data can be repeated if some of these students had already visited the institute. We need to omit on the repeated entries. The company can use the complete data to find out information like the colleges or locations from where maximum enquiries came. By keeping this data the company can find out if there is any slack period for walk in enquiries over the years. The management may require to know which were the months for maximum enquiry and enquiry to enrollment ratio.

If we consider the corporate training business, the company has to know where the industry is going, what kind of expertise will be required in future so that it keeps the staff ready before some competitor takes the chunk. If the company is in this business, then they can also have some trend such as which is slack period, they can keep database of students who have done short term courses and approach them for long duration courses. The board of directors can take decision how to increase the business if they can look at some trend reports or analysis.

For doing all these activities, the company needs some tools, for gathering data, processing data creating reports from the data.

Microsoft provides the suite of tools in one bundle along with the database engine called Business Intelligence Development Studio (commonly called as BIDS). The three main templates are SQL Server Integration Services (SSIS), SQL Server Analysis Services (SSAS) and SQL Server Reporting Services (SSRS). As the names suggest SSIS is used for gathering and integrating data, SSAS for processing and analyzing gathered data and SSRS for creating reports.

Let us concentrate on SQL Server Integration Services first.

SQL Server Integration Services (SSIS)

image

This tool is very useful for gathering data from various sources. As we had already seen in one example where the company fetches students’ data from various places, this data can be any form.

It can be in the form of Excel sheets, access database or even in text files. Before the data is utilized for sending mailers as mentioned above it has to be in uniform format. Some students’ information can be found at multiple places but we need to send them mailer only once. There can be some information which we can omit while creating our database. In order to fetch the data from various sources, doing some cleaning jobs before putting in SQL Server database SSIS provides us various tools.

With SSIS we have a concept called Package which is the basic unit of work. Each SSIS project template can have multiple packages. These packages have extension of dtsx (Data Transformation Services with XML format). With SQL Server the information from package is stored in XML format.

The package will have all the necessary connections as it is the primary task for integrating data. Multiple packages can not share same connection manager. It can be copied from one package to another.

In this package we will have to decide on the flow of the processes for example we will initially fetch the data from flat files (text files), remove unnecessary information, truncate on extra field area and then put the data into SQL Server database. This flow can be specified with the help of Control Flow. This control flow can be called as the flowchart or the workflow. The Control Flow consists of different types of tasks like containers (loops, sequence container), data preparation tasks (data profiling, file system, FTP, XML etc), process communication tasks (execute package, Send mail, MSMQ etc) and the Data Flow Task

Even though the Data Flow Task is a part of Control Flow Task it has a lot of importance. This process is also called as ETL. ETL stands for Extract, Transform and Load. SSIS provides various data sources, destinations and a lot of transform tools. As mentioned sources can vary from excel, text files, XML files, access or even SQL server. Similarly the destinations can be disparate. Depending on how the gathered data is we need various transformation tools. We may have to compute some columns, create some derived columns, sort the data, and change the type for the data etc.

We can use variables with various scopes with packages with which some information can be given on the fly when the package is running. We can log some information; create event handlers for various tasks or when error is generated.

Just creating the package will not be enough, we need to execute it also. For running or executing the package there are various ways. One will be with the help of BIDs itself, second by using command line utilities like DTEXEC or DTEXECUI. We can also deploy the package from test machine to the production machine and run from their by putting it as a part of SQL Server Agent job. Depending on the security policy we can set the restriction about who can execute the package. We can also use configuration files with which certain information can be changed or given at the time of deployment of package.

Once the data is integrated and put at a common place say SQL Server database we can process and analyze the data with the help of analysis services.

SQL Server Analysis Services (SSAS)

image

This tool mainly deals with processing the already gathered information/ data. The data for any organization can be of two types, one which is required for a day to basis and the other which is for historical purposes. If we take the same example of a training organization, we can say that the existing students’ information will be required daily where as the past students’ information will be historical data. Once the student completes a particular course the company does not delete his/her information as it may be required sometime later when we have to send mailers for further courses or organize alumni events. Every organization thus has to maintain 2 different data one called as transactional data (OLTP- Online) and the other called historical or data warehouse.

The main purpose of transactional data is to have faster insertion and updates of data as against the historical data is mainly used for querying purpose. Thus the norms of data integrity, data normalization can be different for the 2 types of data. The size of data is of primary importance for transactional whereas the historical data can grow as much as required. The main requirement of keeping the historical data is the moment any query is fired it should give the instant result. Thus the data can be repeated, computed or aggregated columns can be stored as a part of Data Warehouse data.

The term Data Warehouse stands for the complete data for any organization. There are 2 schools of thoughts for gathering and creating Data Warehouse for any organization. The 2 experts who strongly follow their thoughts are Ralph Kimball and Bill Inmon. Kimball believes that all different departments can create their data storage and then the data can be integrated to form the Data Warehouse (BOTTOM-UP APPROACH). Inmon on the other hand has the opposite approach where once the complete Data Warehouse is ready automatically individual department’s data will also be ready (TOP-DOWN APPROACH). There is no wrong or right way as the final aim is to create and build Data Warehouse. Every organization can decide on its own approach.

With Microsoft SQL Server Analysis Services template we can keep the data in the aggregated in the form of a cube so as to make query processing in least time. This template provides various terms like Data Source, Data Source View, Cubes, Dimension and Fact tables.

While querying data we need information like number of students, total sales figures, total courses conducted which is in numeric form. Just saying 10000 as the number of students will not be meaningful but if we say this figure is for last 6 months or 1 year it will be more meaningful. We can also have information for various students locality wise or college wise in order to get more data.

In these examples we see main two categories one as numeric measures and other as slices and dices against which these numeric measures are queried. Normally table which stores all the information (all students’ data) is called as Fact table. The axis for fact tables is stored in Dimension tables.

The thumb rule can be primary keys are stored I dimension tables (students locality, colleges) and the subsequent secondary keys are stored in fact tables.

We can store this information in already aggregated format in the form of Cubes so as to fetch the data faster. In order to create Cubes first we need to provide the source from which the data is gathered.

With Data Source we can specify the provider from where the data comes which can be in the form of SQL Server database, DB2, Oracle or even hierarchical format.

Once the Data Source is set we can create a window for looking at the data. Suppose the SQL Server Database from where data is fetched consists of 50 tables, whereas our requirement is only for the data coming from Human Resources department. So we can create a window/ view which comprises of only those table which are required. Another advantage of DSV (Data Source View) can be if the tables are not related in the database we can establish the logical relationship. We can also create computed columns, thus the data can be manipulated without affecting the original data.

The different tables as a part of DSV can be of two types either Star schema or snowflake schema. The star schema specifies there is a single fact table and multiple dim tables related to it which looks like a star. In snowflake as the name suggest, one dim table can act as a fact for another dim table thus forming snowflake.

Once a cube is created it can be deployed on the Analysis Services server from where it can be queried by browsing or creating reports on it. We can specify whether the data in the cube should be automatically updated once the underlying fact or dim tables data is changed or not. This is possible by setting the storage settings as MOLAP (multidimensional OLAP), ROLAP (Realtime / Relational OLAP) or HOLAP (Hybrid OLAP).

A cube comprises of fact tables and dim tables. Maximum data will be stored in fact. When the storage becomes very high in volume it can be stored across multiple partitions. The numeric measures are provided from fact tables while the dim tables provide the primary keys based on which the data can be sliced and queried. Mostly for every cube a special type of dimension is required called Time Dimension. The data with time or to be specific date can be sliced by giving time attributes like month, quarter, semester or even year.

As already mentioned the data can be kept in already aggregated format in Analysis services server so as to query it faster. We have to keep in mind a very important factor that the data in Data Warehouse should be periodically updated from the transactional data. Thus for this periodic updating, we may have to go back to SSIS to fetch data.

Once the data is processed we need to present it in a user friendly manner so that certain decisions can be taken. The data can be presented in the form of pure HTML, Excel sheet, PDF or in the form of chart. This job can be achieved by Reporting Services

SQL Server Reporting Services (SSRS)

image

With the help of BIDS (Business Intelligence Development Studio) there are various templates provides for reports, Report Server Project, Report Server Wizard, Report Model project. The first 2 are for creating reports and the third will be used to create a report model based on which ad-hoc report can be created using Report Builder.

For creation of any report first we will require the data on which the report is based on. Like with SSAS we can create Data source for report. The data can be fetched from OLTP database, OLAP database, any other database like Oracle, Teradata or even on hierarchical data. The Data Source can be shared across multiple reports or can be different for different reports depending upon the requirements. The reports created are stored in XML format with the extension as RDL which stands for Report Description/Definition Language.

There report can be created by using a wizard which will provide step by step report creation followed by certain format for report after creation. Once the report created can be viewed with the help of preview tab from BIDS. The report can be deployed on Report Server which by default is rendered in HTML format. Before deploying the report we need to specify the Target Server URL for Report Server which is as follows

http://<machine Name>/ReportServer (in case of default instance)

Or

http://<machine name>/ReportServer_<instance name> (in case of non default or named instance)

The _ will be replaced by $ in SQL Server 2005.

For creation of reports without using wizard reports there are various controls provided like Table, Matrix, Chart, List and Tablix (which is combination of Table and Matrix). The field list from a data source can be specified which can also comprise of parameters if required. For creation of dataset query analyzer is provided with the help of which we can select the different tables and the respective fields from them. If the tables are related in the database the relationship will be automatically fetched, if not it can be created.

We can specify default and available values for parameters used. These values can be some constant values or it can be from a query. The parameter can have multiple values if specified. In order to get the parameters data from another query we can create another dataset in the same report.

As already mentioned once reports created they can be deployed to the server with the help of BIDS. All reports can be deployed in one go. Another deployment method is to start Report Server and then choose the tab for Upload file. We can programmatically deploy reports by using rs utility.

It may that after seeing a particular report or trend, the management requests for some other report. In order to create the new report we may have to go back to integration stage and thus SSIS, SSAS and SSRS continue in cyclic manner.

Summary

In this article we discussed general concepts of Business Intelligence. Business Intelligence comprises of various tools which are used for gathering, storing, analyzing and providing access to information required for better understanding for organizations. These analysis and reports can be used for betterment of the organization. How every organization needs to use Business Intelligence. Later we talked about the 3 mail tools provided by Microsoft SQL Server called Integration Services, Analysis Services and Reporting Services. We also saw the main features provided by these tools.

Find First and Last Day of the Current Quarter in SQL Server

I was recently working on a requirement where the user wanted a report with data from the First day to the Last Day of the current Quarter

Here's a simple way to find the Find First and Last Day of the current quarter in SQL Server 2005/2008


SELECT DATEADD(qq,DATEDIFF(qq,0,GETDATE()),0) as FirstDayOfQuarter


SELECT DATEADD(qq,DATEDIFF(qq,-1,GETDATE()),-1) as LastDayOfQuarter




OUTPUT


FirstDayOfQuarter         LastDayOfQuarter


2009-04-01 00:00:00.000   2009-06-30 00:00:00.000


Finding the date last year based on the current week and weekday using SQL Server

Today is the 21st of May, 2009 and it is a Thursday today. Have you wondered what date was Thursday last year in the same week? Here's a very handy query by Hector which displays the last year's date based on the current weekday and current week


SELECT DATEADD(day, (DATEPART(week, GETDATE()) * 7


+ DATEPART(weekday, GETDATE()))


- (DATEPART(week, DATEADD(year, -1, GETDATE())) * 7


+  DATEPART(weekday, DATEADD(year, -1, GETDATE()))), DATEADD(year, -1, GETDATE())) as LastYearDate




RESULT


LastYearDate


2008-05-22 11:14:26.350


Find First and Last Day Of Each Month

The first day of each month is always 1. However if you interested to find the First and Last Date of each month using a T-Sql Query, here it is:

-- Return First and Last Date of a Month
DECLARE @Month smallint
SET @Month = 1

SELECT DAY(DATEADD(Month, DATEDIFF(Month, -1, getdate()) - 2, -1) + 1) as FirstDayofMonth,
DAY(DATEADD(Month, DATEDIFF(Month,0,getdate())+@Month, -1)) as LastDayOfMonth

If you wish to find out the Lastday of the previous month, just set @Month to 0.

Note: The value for @Month depends on the current month you are in. So if this month is September, the value of @Month is 1. Similarly for Oct(2), Nov(3), Dec(4), Jan(5), Feb(6) and so on.

Also read SQL Server: First and Last Sunday of Each Month

Find Last Day Of a Month in SQL Server 2005

Let us see how to find out the last day of a month :

-- Return Last Date of a Month
DECLARE @Month smallint
SET @Month = 1
SELECT DATEADD(Month, DATEDIFF(Month,0,getdate())+@Month, -1) as LastDateOfMonth,
DAY(DATEADD(Month, DATEDIFF(Month,0,getdate())+@Month, -1)) as LastDayOfMonth

The @Month accepts the month that needs to be added as the third parameter of the DATEADD function. You can set different values as shown below to view the last day of the month

1 - Current Month
0 - Last Month
2 - Next Month