Output in special format - sql-server

May any one please help me how to code the below scenerio in sql.
DECLARE #T TABLE
(
Year VARCHAR (50),
Month VARCHAR (50),
GROUPS VARCHAR (50),
SALESPERNO VARCHAR (50),
Net VARCHAR (50)
)
INSERT #T
SELECT '2014','1','A','6607','109.34' UNION ALL
SELECT '2014','2','A','6607','13.42' UNION ALL
SELECT '2014','3','A', '6607','359.41' UNION ALL
SELECT '2014','1','A', '6608','99.52' UNION ALL
SELECT '2014','2','A','6608','95.62' UNION ALL
SELECT '2014','3','A', '6608','89.63' UNION ALL
SELECT '2014','1','B','8888','340.95' UNION ALL
SELECT '2014','2','B','8888','652.25' UNION ALL
SELECT '2014','3','B','8888','352.26'
SELECT * FROM #T
Here: month 1 = Jan, 2=feb, 3=mar
Output is sum of net for a particular salesperno and groups for jan feb mar and total like this:
January| February | March| QFY | SALES_GROUP |SALESPERSON_NUMBER
109.34 | 13.42 | 359.41| 482.17| A | 6607
99.52 | 95.62 | 89.63 | 284.77| A | 6608
340.95 | 652.25 | 352.26| 1345.46| B | 8888

You can do this in multiple ways. As Tab Alleman suggested one way is with the help of CASE and GROUP BY.
select
SUM(CASE WHEN [Month]=1 THEN [NET] END) [January],
SUM(CASE WHEN [Month]=2 THEN [NET] END) [February],
SUM(CASE WHEN [Month]=3 THEN [NET] END) [March],
SUM([NET]) [QFY],
[GROUPS] [SALES_GROUP],
[SALESPERNO] [SALESPERSON_NUMBER]
from #T
group by
[GROUPS],
[SALESPERNO]
This is another way, with PIVOT
SELECT
[1] [January],
[2] [February],
[3] [March],
[1]+[2]+[3] [QFY],
[GROUPS] [SALES_GROUP],
[SALESPERNO] [SALESPERSON_NUMBER]
FROM #T
PIVOT (
SUM(NET)
FOR [Month] in ([1],[2],[3])
) pvt

Related

Pivoting table in SQL

i have a problem with approach how to pivot this table:
How can i convert this:
Would you be kind enough give me hints (not whole code) how to do this? i really dont know where should i start (i dont know whether it is typical pivoting unpivoting)
+------+------+--------+----------+-----------+-----+
| ColI | Col2 | Month | Turnover | Provision | Fee |
+------+------+--------+----------+-----------+-----+
| 123 | Asdf | 201810 | 10000 | 100 | 0,1 |
| 123 | Asdf | 201811 | 20000 | 200 | 0,2 |
| 123 | Asdf | 201812 | 30000 | 300 | 0,3 |
+------+------+--------+----------+-----------+-----+
into this:
+------+------+---------------+-----------------+------------+---------------+-----------------+------------+---------------+-----------------+-----------+
| ColI | Col2 | Turnover20810 | Provision201810 | Fee201810 | Turnover20811 | Provision201811 | Fee201811 | Turnover20812 | Provision201812 | Fee201812 |
+------+------+---------------+-----------------+------------+---------------+-----------------+------------+---------------+-----------------+-----------+
| 123 | Asdf | 10000 | 100 | 0,1 | 20000 | 200 | 0,2 | 30000 | 300 | 0,3 |
+------+------+---------------+-----------------+------------+---------------+-----------------+------------+---------------+-----------------+-----------+
Thank you!
Assuming that each ColI, Col2 group would only have a maximum of three records, then we can try pivoting using the help of ROW_NUMBER:
WITH cte AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY ColI, Col2 ORDER BY Month) rn
FROM yourTable
)
SELECT
ColI,
Col2,
MAX(CASE WHEN rn = 1 THEN Turnover END) AS Turnover1,
MAX(CASE WHEN rn = 1 THEN Provision END) AS Provision1,
MAX(CASE WHEN rn = 1 THEN Fee END) AS Fee1,
MAX(CASE WHEN rn = 2 THEN Turnover END) AS Turnover2,
MAX(CASE WHEN rn = 2 THEN Provision END) AS Provision2,
MAX(CASE WHEN rn = 2 THEN Fee END) AS Fee2,
MAX(CASE WHEN rn = 3 THEN Turnover END) AS Turnover3,
MAX(CASE WHEN rn = 3 THEN Provision END) AS Provision3,
MAX(CASE WHEN rn = 3 THEN Fee END) AS Fee3
FROM cte
GROUP BY
ColI,
Col2;
Note that I did not hardwire more specific column names, to keep the query as general as possible. For example, perhaps there might be another ColI, Col2 group which would have a different three months.
By using Dynamic Sql
IF OBJECT_ID('tempdb..#TEMP') IS NOT NULL
DROP TABLE #TEMP
;WITH CTE (ColI , Col2 , Month , Turnover , Provision , Fee )
AS
(
SELECT 123 , 'Asdf' , 201810 , 10000 ,100 ,'0,1' UNION ALL
SELECT 123 , 'Asdf' , 201811 , 20000 ,200 , '0,2' UNION ALL
SELECT 123 , 'Asdf' , 201812 , 30000 ,300 , '0,3'
)
SELECT ColI , Col2,Turnover , Provision , Fee,MixedCol,Reqcol , ROW_NUMBER()OVER(ORDER BY (SELECT NULL)) AS Seq
INTO #Temp
FROM CTE
CROSS APPLY (VALUES (CONCAT('Turnover','_',[Month]),CAST(Turnover AS VARCHAR(20))),
(CONCAT('Provision','_',[Month]),CAST(Provision AS VARCHAR(20))),
(CONCAT('Fee','_',[Month]),CAST(Fee AS VARCHAR(20)))
)DT (MixedCol,Reqcol)
DECLARE #Sql nvarchar(max),
#DynamicColumn nvarchar(max),
#MaxDynamicColumn nvarchar(max)
SELECT #DynamicColumn = STUFF((SELECT ', '+QUOTENAME(CAST(MixedCol AS VARCHAR(100)))
FROM #TEMP ORDER BY Seq FOR XML PATH ('')),1,1,'')
SELECT #MaxDynamicColumn = STUFF((SELECT ', '+'MAX('+QUOTENAME(CAST(MixedCol AS VARCHAR(100)))+') AS '+QUOTENAME(CAST(MixedCol AS VARCHAR(100)))
FROM #TEMP ORDER BY Seq FOR XML PATH ('')),1,1,'')
SET #Sql=' SELECT ColI , Col2,'+ #MaxDynamicColumn+'
FROM
(
SELECT * FROM #TEMP
)AS src
PIVOT
(
MAX(Reqcol) FOR [MixedCol] IN ('+#DynamicColumn+')
) AS Pvt
GROUP BY ColI , Col2 '
EXEC (#Sql)
PRINT #Sql
Q: "...give me hints (not whole code) how to do this"
A: This example with dynamic transpose of table. You can try this. Unpivot your original table and transpose.
CREATE table #tbl (
color varchar(10), Paul int, John int, Tim int, Eric int);
insert #tbl select
'Red' ,1 ,5 ,1 ,3 union all select
'Green' ,8 ,4 ,3 ,5 union all select
'Blue' ,2 ,2 ,9 ,1;
select * FROM #tbl
--1) Transpose. Example without dynamic code. You create list of fields in query
select *
from #tbl
unpivot (value for name in ([Paul],[John],[Tim],[Eric])) up
pivot (max(value) for color in ([Blue],[Green],[Red])) p
--2) Transpose. Example with dynamic code, without names of fields.
DECLARE #cols NVARCHAR(MAX), #query NVARCHAR(MAX), #rows NVARCHAR(MAX)='';
-- XML with all values
SET #cols = STUFF(
(
SELECT DISTINCT
','+QUOTENAME(T.Color) -- Name of first column
FROM #tbl T FOR XML PATH(''), TYPE
).value('.', 'nvarchar(max)'), 1, 1, '');
SELECT #rows=#rows+','+QUOTENAME(Name)
FROM
(SELECT Name,ROW_NUMBER() OVER(ORDER BY column_id) AS 'RowNum'
FROM tempdb.sys.Columns
WHERE Object_ID = OBJECT_ID('tempdb..#tbl')
) AS A WHERE A.RowNum>1
SET #rows=STUFF(#rows,1,1,'')
SET #query='SELECT *
from #tbl
unpivot (value for name in ('+#rows+')) up
pivot (max(value) for color in ('+#Cols+')) p'
EXEC (#query)

Get current month details in sql. Like, how many weeks in month?, Count of weekdays with there name?

Today randomly one thought came, to make one dynamic query which get all the details of current month into one table, suppose if current month is May 2017, then the output table should be like this:
Details | Count
-----------------|------------
First Date | 05-01-2017
Last Date | 05-31-2017
Count of Mon | 5
Count of Tues | 5
Count of Wed | 5
Count of Thur | 4
Count of Fri | 4
Count of Sat | 4
Count of Sun | 4
By combining the next Links:-
How can I select the first day of a month in SQL?
SQL Query to find the last day of the month
Count how many Sundays, Mondays, Tuesdays... in current month using MS SQL
Try the next code:-
declare #T table(Details varchar(100) , Result varchar(100));
WITH CTE AS
(
SELECT DATEADD(D,-DATEPART(D,GETDATE())+1,GETDATE())[FIRST SUNDAY DATE],DATENAME(DW,DATEADD(D,-DATEPART(D,GETDATE())+1,GETDATE()))[DAY NAME]
UNION ALL
SELECT DATEADD(D,1,[FIRST SUNDAY DATE]),DATENAME(DW,DATEADD(D,1,[FIRST SUNDAY DATE]))FROM CTE WHERE [FIRST SUNDAY DATE]<=DATEADD(D,-DATEPART(D,GETDATE()),DATEADD(M,1,GETDATE()))-1
)
insert into #T(Details , Result)
SELECT [DAY NAME],COUNT([DAY NAME]) as 'COUNT' FROM CTE GROUP BY [DAY NAME]
Update #T
set Details = 'Count OF ' + Details
SELECT 'First Date' 'Details', convert(varchar(100),DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0),101) 'Count'
Union all
select 'Last Date' , convert(varchar(100),dateadd(month,1+datediff(month,0,GETDATE()),-1),101)
union all
select * from #T
Result:-
IF OBJECT_ID('Tempdb..#MonthDetails') IS NOT NULL
Drop Table #MonthDetails
Declare #monthdate DATE ='05-5-2017'--Provide date
SET #monthdate =CONVERT(VARCHAR(10), #monthdate, 105)
DECLARE #y INT = DATEPART(YEAR,#monthdate),
#EndOFMonth Varchar(10),
#StartOfMonth Varchar(10)
CREATE TABLE #MonthDetails(ID Int IDENTITY,[MonthName] Varchar(10),EndOFMonth Varchar(10),StartOfMonth Varchar(10)
,[Mon] INT,[Tue] INT,[Wed] INT,[Thu] INT, [Fri] INT,[Sat] INT,[Sun] INT,[Sum] INT)
SET #EndOFMonth= CONVERT(VARCHAR(10),EOMONTH(#monthdate),105)
SET #StartOfMonth=CONVERT(VARCHAR(10),DATEADD(month, DATEDIFF(month, 0, #monthdate), 0),105)
DECLARE #d DATETIME = dateadd(year, #y - 1900, 0)
;WITH CTE
AS
(
SELECT 1 A,
LEFT(DATENAME(WEEKDAY, #D), 3) B,
DATENAME(MONTH, 0) MONTH,
1 SORT
UNION ALL
SELECT A + 1 A,
LEFT(DATENAME(WEEKDAY, #D + A), 3) B,
DATENAME(MONTH, #D + A) MONTH,
DATEPART(MONTH, #D + A) SORT
FROM CTE WHERE A < DATEPART(DAYOFYEAR, DATEADD(YEAR, 1, #D)-1)
)
INSERT INTO #MonthDetails([MonthName],EndOFMonth,StartOfMonth,[Mon],[Tue],[Wed],[Thu],[Fri],[Sat],[Sun],[Sum])
SELECT [MONTH],
#EndOFMonth,
#StartOfMonth,
[Mon],[Tue],[Wed],[Thu],[Fri],[Sat],[Sun],
[Mon]+[Tue]+[Wed]+[Thu]+[Fri]+[Sat]+[Sun] [Sum]
FROM cte
PIVOT (COUNT(a) FOR [b] IN ([Mon],[Tue],[Wed],[Thu],[Fri],[Sat],[Sun],[Sum])) AS pvt WHERE [MONTH]=DATENAME(MM,#monthdate)
ORDER BY sort
OPTION (MAXRECURSION 366)
;With Result
AS
(
SELECT ISNULL(NULL,'FirstDate') AS Details ,StartOfMonth AS [Count] FROM #MonthDetails UNION ALL
SELECT ISNULL(NULL,'LastDate') ,EndOFMonth FROM #MonthDetails UNION ALL
SELECT ISNULL(NULL,'Count of Mon') , CAST([Mon] AS VARCHAR(5)) FROM #MonthDetails UNION ALL
SELECT ISNULL(NULL,'Count of Tues') , CAST([Tue] AS VARCHAR(5)) FROM #MonthDetails UNION ALL
SELECT ISNULL(NULL,'Count of Wed') , CAST([Wed] AS VARCHAR(5)) FROM #MonthDetails UNION ALL
SELECT ISNULL(NULL,'Count of Thur') , CAST([Thu] AS VARCHAR(5)) FROM #MonthDetails UNION ALL
SELECT ISNULL(NULL,'Count of Fri') , CAST([Fri] AS VARCHAR(5)) FROM #MonthDetails UNION ALL
SELECT ISNULL(NULL,'Count of Sat') , CAST([Sat] AS VARCHAR(5)) FROM #MonthDetails UNION ALL
SELECT ISNULL(NULL,'Count of Sun') , CAST([Sun] AS VARCHAR(5)) FROM #MonthDetails UNION ALL
SELECT ISNULL(NULL,'Total Days Of Month'),CAST([Sum] AS VARCHAR(5)) FROM #MonthDetails
)
SELECT * from Result
Output
Details |Count
-------------------------------------
FirstDate |01-01-2017
LastDate |31-01-2017
Count of Mon |5
Count of Tues |5
Count of Wed |4
Count of Thur |4
Count of Fri |4
Count of Sat |4
Count of Sun |5
Total Days Of Month |31

Group by a set of Values (Check-In or Check-Out)

I have a simple table which records people clocking-in and clocking out like so.
Id | EmployeeNumber | InOutId | InOutDateTime
-----------------------------------------------------
1 | 505 | IN | 2015-03-24 08:32:42:000
1 | 506 | IN | 2015-03-24 08:35:47:000
1 | 507 | IN | 2015-03-24 08:46:12:000
1 | 505 | OUT | 2015-03-24 16:59:00:000
1 | 506 | OUT | 2015-03-24 17:05:00:000
I want to show the total people currently IN and those currently OUT. In other words:
- Total IN means those that do not have a corresponding OUT for that given day. - Total OUT means those that do have an IN and an OUT for that given day.
So, based on my table above, I want to get the following results:
TotalCurrentlyIn | TotalCurrentlyOut
-----------------------------------------
1 | 2
This is what I have so far:
DECLARE #d date;
set #d = cast('2015-03-24 15:02:42.000' as date)
select EmployeeNumber, InOutId, InOutDateTime from MyAttendance
where
InOutDateTime >= DATEADD(day, DATEDIFF(day, 0, #d), 0)
and InOutDateTime < DATEADD(day, DATEDIFF(day, 0, #d) +1, 0)
order by
EmployeeNumber, InOutId
I need to be able to sum and group by - any ideas?
try,
DECLARE #d date;
set #d = cast('2015-03-24 15:02:42.000' as date)
;with cte as(
select t.EmployeeNumber,t.InOutId as in1,
t1.InOutId out1,t.InOutDateTime from #t t
left join (select EmployeeNumber,InOutId,InOutDateTime from #t
where InOutId='OUT' and cast(InOutDateTime as date)=cast(#d as date) ) t1
on t.EmployeeNumber=t1.EmployeeNumber and
cast(t.InOutDateTime as date)=cast(t1.InOutDateTime as date)
where t.InOutId='IN' and cast(t.InOutDateTime as date)=cast(#d as date))
select count(in1) Totalin,count(out1) Totalout, sum(case when out1 is null then 1 else 0 end) TotalCurrentlyIn
,count(out1) TotalCurrentlyOut from cte
data
declare #t table (Id int,EmployeeNumber int, InOutId varchar(3), InOutDateTime datetime)
insert into #t(Id, EmployeeNumber,InOutId, InOutDateTime) values
(1 , 505 , 'IN' , '2015-03-24 08:32:42:000'),
(1 , 506 , 'IN' , '2015-03-24 08:35:47:000'),
(1 , 507 , 'IN' , '2015-03-24 08:46:12:000'),
(1 , 505 , 'OUT' , '2015-03-24 16:59:00:000'),
(1 , 506 , 'OUT' , '2015-03-24 17:05:00:000')
CheckIn = 1 and CheckOut = 2 so you need to check last entry of all the uses.
Select EmployeeId, ActionType, Max(ActionDateTime)
From AttendanceLog
Where
ActionDateTime >= DATEADD(day, DATEDIFF(day, 0, #d), 0)
and ActionDateTime < DATEADD(day, DATEDIFF(day, 0, #d) +1, 0)
Group by
EmployeeId, ActionType
Order by
EmployeeId,ActionType
If I understand the question. you need to know how much person is in the office right now:
the first query return the max date for any employee, than you join it with the actionType
select
EmployeeId , max(ActionDateTime) as MaxActionDateTime into #temptable
from table
group by EmployeeId
select count (EmployeeId), ActionType
from table inner join #temptable
on table.EmployerId == #temptable.EmployerId
and table.ActionDateTime == #temptable.MaxActionDateTime
group by ActionType
Using a windowing function you can get the last action for every employee and count those
With data As (
Select id, EmployeeNumber, InOutId
, lastAction = ROW_NUMBER() OVER (PARTITION BY EmployeeNumber
ORDER BY InOutDateTime DESC)
From table1
)
Select Count(CASE InOutId WHEN 'IN' THEN 1 END) TotalCurrentlyIn
, Count(CASE InOutId WHEN 'OUT' THEN 1 END) TotalCurrentlyOut
From data
Where lastAction = 1

sql query to create columns with arithmetic expressions

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);
INSERT #ABC VALUES (2013,2,3);
INSERT #DEF VALUES (2013,1,4);
INSERT #DEF VALUES (2013,1,5);
INSERT #DEF VALUES (2013,2,6);
INSERT #GHI VALUES (2013,1,7);
INSERT #GHI VALUES (2013,1,8);
INSERT #GHI VALUES (2013,2,9);
INSERT #GHI VALUES (2013,3,10);
My current query is
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)
FROM #DEF
WHERE [Year] = T.[Year]
AND [Month] = T.[Month]) AS [Sum_SalesStores],
(SELECT SUM(Products)
FROM #GHI
WHERE [Year] = T.[Year]
AND [Month] = T.[Month]) AS [Sum_Products]
FROM (
-- this selects a list of all possible dates.
SELECT [Year],
[Month]
FROM #ABC
UNION
SELECT [Year],
[Month]
FROM #DEF
UNION
SELECT [Year],
[Month]
FROM #GHI) AS T;
Which returns
+------+-------+------------+-----------------+--------------+
| Year | Month | Sum_Stores | Sum_SalesStores | Sum_Products |
+------+-------+------------+-----------------+--------------+
| 2013 | 1 | 3 | 9 | 15 |
| 2013 | 2 | 3 | 6 | 9 |
| 2013 | 3 | NULL | NULL | 10 |
+------+-------+------------+-----------------+--------------+
What I want to do is to add two more columns to my query which shows
Sum_SalesStores/Sum_Products & Sum_SalesStores/Sum_Stores per each month and then sort the query based on the two expressions. Can anyone tell me how its possible ?
One way would just be to chuck your entire existing query into a CTE then you can select from that and perform the calculations.
;WITH CTE
AS (
/*Paste your existing query*/
)
SELECT *,
Sum_SalesStores / Sum_Products AS Foo,
Sum_SalesStores / Sum_Stores AS Bar
FROM CTE
ORDER BY Foo,
Bar
I re-factored your code a bit to place the core of the logic in the FROM statement.
SELECT Dates.[Year]
,Dates.[Month]
,SumStores
,SumSalesStores
,SumProducts
,SumSalesStores/SumProducts
,SumSalesStores/SumStores
FROM
(
-- This selects a list of all possible dates.
SELECT [Year],[Month] FROM ABC
UNION SELECT [Year],[Month] FROM DEF
UNION SELECT [Year],[Month] FROM GHI
) AS Dates
Left Join
(
SELECT [Year]
,[Month]
,SumStores = Sum(Stores)
FROM ABC
GROUP BY [Year]
,[Month]
) As Stores
On Dates.[Year] = Stores.[Year]
And Dates.[Month] = Stores.[Month]
Left Join
(
SELECT [Year]
,[Month]
,SumSalesStores = Sum(SalesStores)
FROM DEF
GROUP BY [Year]
,[Month]
) As SalesStores
On Dates.[Year] = SalesStores.[Year]
And Dates.[Month] = SalesStores.[Month]
Left Join
(
SELECT [Year]
,[Month]
,SumProducts = Sum(Products)
FROM GHI
GROUP BY [Year]
,[Month]
) As Products
On Dates.[Year] = Products.[Year]
And Dates.[Month] = Products.[Month]
ORDER BY 1, 2
Here's the SQL Fiddle.

Fetching Records from multiple tables month wise

I am having scenario like this : I am having many tables and each table has date fields.
Table: FA
Id | Created_Date |
------------------------
1 | 1/12/2012 |
2 | 2/15/2012 |
3 | 2/25/2012 |
Table: TPA
Id | Created_Date |
------------------------
1 | 3/10/2012 |
2 | 4/25/2012 |
3 | 5/20/2012 |
4 | 5/21/2012 |
Table: Gift
Id | Created_Date |
------------------------
1 | 6/10/2012 |
2 | 7/25/2012 |
3 | 8/10/2012 |
3 | 7/11/2012 |
I want output like I want total count of records from each table and display it respective to month wise by using Created_Date field dates.
Expected Output like this:
Give this solution a try,
SELECT MonthName,
COALESCE(FA, 0) FA,
COALESCE(TPA, 0) TPA,
COALESCE(GIFT, 0) GIFT
FROM
(
SELECT monthList.ordby,
monthList.MonthName,
org.TableName,
org.TotalCount
FROM
(
SELECT 1 ordby, 'January' MonthName UNION SELECT 2, 'February' UNION
SELECT 3, 'March' UNION SELECT 4, 'April' UNION
SELECT 5,'May' UNION SELECT 6,'June' UNION
SELECT 7,'July' UNION SELECT 8,'August' UNION
SELECT 9,'September' UNION SELECT 10,'October' UNION
SELECT 11,'November' UNION SELECT 12,'December'
) monthList
LEFT JOIN
(
SELECT 'FA' TableName,
DATENAME(mm,Created_Date) MonthName,
COUNT(*) TotalCount
FROM FA
GROUP BY DATENAME(mm,Created_Date)
UNION
SELECT 'TPA' TableName,
DATENAME(mm,Created_Date) MonthName,
COUNT(*) TotalCount
FROM TPA
GROUP BY DATENAME(mm,Created_Date)
UNION
SELECT 'Gift' TableName,
DATENAME(mm,Created_Date) MonthName,
COUNT(*) TotalCount
FROM Gift
GROUP BY DATENAME(mm,Created_Date)
) org ON monthList.MonthName = org.MonthName
) data
PIVOT
(
MAX(TotalCount)
FOR TableName IN ([FA], [TPA],[GIFT])
) head
ORDER BY ordby
http://www.sqlfiddle.com/#!3/dc613/14
I was trying to get the Find the solution since last 4 Hours
I think my answer is Low in Performance as Compare to above Answer,
create table #month
(
id [int] IDENTITY(1,1) NOT NULL,
[month] varchar(3)
)
DBCC CHECKIDENT(#month, RESEED, 1)
insert into #month
values
('Jan'),
('Feb'),
('Mar'),
('Apr'),
('May'),
('Jun'),
('Jul'),
('Aug'),
('Sep'),
('Oct'),
('Nov'),
('Dec')
declare #id int
set #id=1
declare #month varchar(3)
declare #sql nvarchar(max)
set #sql=''
declare #order varchar(3)
while (#id<13)
BEGIN
set #month=(select [month] from #month where id=#id)
set #order=CONVERT(varchar(3),#id)
set #sql=#sql+'insert into #display
(
[Month],
[COUNT(FA)],
[COUNT(TPA)],
[COUNT(Gift)],
[ORDER]
)
select '''+ #month +''' AS [Month],
(select
COUNT(CONVERT(VARCHAR(3), DATENAME(MM,Created_Date), 100))
from FA
where CONVERT(VARCHAR(3), DATENAME(MM,Created_Date), 100)='''+ #month +''') [COUNT(FA)],
(select
COUNT(CONVERT(VARCHAR(3), DATENAME(MM,Created_Date), 100))
from TPA
where CONVERT(VARCHAR(3), DATENAME(MM,Created_Date), 100)='''+ #month +''') [COUNT(TPA)],
(select
COUNT(CONVERT(VARCHAR(3), DATENAME(MM,Created_Date), 100))
from Gift
where CONVERT(VARCHAR(3), DATENAME(MM,Created_Date), 100)='''+ #month +''') [COUNT(Gift)],
'''+ #order + ''' [Order]
'
set #id=#id+1 --Incrementing the month
END
exec sp_executesql #sql
print #sql
select [MONTH],
[COUNT(FA)],
[COUNT(TPA)],
[COUNT(Gift)]
from #display
order by convert(int,[ORDER])

Resources