So I've got data like so
id type date
1 1 2015-02-04
2 1 2015-02-04
3 2 2015-02-04
4 1 2015-02-05
5 2 2015-02-06
And I want a result like so
countForType1 countForType2 dow
2 1 Wednesday
1 0 Thursday
0 1 Friday
etc...
I'm trying use the OVER(PARTITION but I think I'm using it incorrectly, or possibly, I need to use something else. Here is my current query:
SELECT
COUNT(seatType) OVER(PARTITION BY seatType) AS Counts,
CASE DATEPART(DW,testDate)
WHEN 1 THEN 'Sunday'
WHEN 2 THEN 'Monday'
WHEN 3 THEN 'Tuesday'
WHEN 4 THEN 'Wednesday'
WHEN 5 THEN 'Thursday'
WHEN 6 THEN 'Friday'
WHEN 7 THEN 'Saturday'
END dow
FROM tst_Tests
WHERE roomid = 1
GROUP BY DATEPART(DW,testDate), seatType
I'm not sure how to create a second column counting by an individual seat types.
I'm thinking I could just put two select statements inside the select statement, but that seems inefficient. I feel like there is a function for this I am using incorrectly or not at all.
EDIT: I made the example data match actual dates and numbers of what would be returned.
You should use Conditional Aggergate instead of window function
SELECT Count(CASE WHEN type = 1 THEN 1 END) AS countForType1,
Count(CASE WHEN type = 2 THEN 1 END) AS countForType2,
CASE
WHEN Datepart(DW, date) = 1 THEN 'Sunday'
WHEN Datepart(DW, date) = 2 THEN 'Monday'
WHEN Datepart(DW, date) = 3 THEN 'Tuesday'
WHEN Datepart(DW, date) = 4 THEN 'Wednesday'
WHEN Datepart(DW, date) = 5 THEN 'Thursday'
WHEN Datepart(DW, date) = 6 THEN 'Friday'
WHEN Datepart(DW, date) = 7 THEN 'Saturday'
END dow
FROM Yoursampletable
GROUP BY Datepart(DW, date)
Like this?
DECLARE #Example TABLE ([Id] int, [type] int, [testDate] date)
INSERT INTO #Example ([Id], [type], [testDate])
SELECT 1,1,'2015-02-04' UNION ALL
SELECT 2,1,'2015-02-04' UNION ALL
SELECT 3,2,'2015-02-04' UNION ALL
SELECT 4,1,'2015-02-05' UNION ALL
SELECT 5,2,'2015-02-06'
;with rowsWithDayName as (
select *,
CASE WHEN DATEPART(DW,testDate) = 1 THEN 'Sunday'
WHEN DATEPART(DW,testDate) = 2 THEN 'Monday'
WHEN DATEPART(DW,testDate) = 3 THEN 'Tuesday'
WHEN DATEPART(DW,testDate) = 4 THEN 'Wednesday'
WHEN DATEPART(DW,testDate) = 5 THEN 'Thursday'
WHEN DATEPART(DW,testDate) = 6 THEN 'Friday'
WHEN DATEPART(DW,testDate) = 7 THEN 'Saturday'
END as [DayName]
from #Example
)
select
SUM(CASE WHEN [type]=1 THEN 1 ELSE 0 END) as countForType1
, SUM(CASE WHEN [type]=2 THEN 1 ELSE 0 END) as countForType2
, [DayName]
FROM rowsWithDayName
group by [DayName]
Related
How can I add row and column grand totals in the table below?
I want to get total and grand total by months.
However, I couldn't do that.
SELECT *
FROM(
SELECT
YEAR(DueDate) [Year],
CASE MONTH(DueDate)
WHEN 1 THEN 'January'
WHEN 2 THEN 'February'
WHEN 3 THEN 'March'
WHEN 4 THEN 'April'
WHEN 5 THEN 'May'
WHEN 6 THEN 'June'
WHEN 7 THEN 'July'
WHEN 8 THEN 'August'
WHEN 9 THEN 'September'
WHEN 10 THEN 'October'
WHEN 11 THEN 'November'
WHEN 12 THEN 'December'
END as [Month],
ProductID,
OrderQty
FROM Production.WorkOrder
) WorkOrders
PIVOT
(
SUM(OrderQty)
FOR [Month] IN (
[January],[February],[March],[April],
[May],[June],[July],[August],
[September],[October],[November],[December]
)
) AS PivotTable
ORDER BY [Year], ProductID
Stuff like this is far easier using a conditional aggregate over the restrictive PIVOT operator.
Without sample data, nor expected results, this isn't tested, but you should be able to achieve what you're after with something like this:
SELECT CASE WHEN GROUPING(DATEPART(YEAR,DueDate)) = 0 THEN
CAST(DATEPART(YEAR,DueDate) AS varchar(50))
ELSE 'GrandTotal' END AS [Year],
SUM(CASE DATEPART(MONTH,DueDate) WHEN 1 THEN OrderQty END) AS January, --Don't use single quotes for alaises,
SUM(CASE DATEPART(MONTH,DueDate) WHEN 2 THEN OrderQty END) AS Feburary, --it can be very confusing to read.
SUM(CASE DATEPART(MONTH,DueDate) WHEN 3 THEN OrderQty END) AS March, --Single quotes are for literal strings.
SUM(CASE DATEPART(MONTH,DueDate) WHEN 4 THEN OrderQty END) AS April, --Using ' for alias only work in the SELECT too,
SUM(CASE DATEPART(MONTH,DueDate) WHEN 5 THEN OrderQty END) AS May, --something like ORDER BY 'January' would not
SUM(CASE DATEPART(MONTH,DueDate) WHEN 6 THEN OrderQty END) AS June, --order by data by the column aliases as 'January'.
SUM(CASE DATEPART(MONTH,DueDate) WHEN 7 THEN OrderQty END) AS July,
SUM(CASE DATEPART(MONTH,DueDate) WHEN 8 THEN OrderQty END) AS August,
SUM(CASE DATEPART(MONTH,DueDate) WHEN 9 THEN OrderQty END) AS September,
SUM(CASE DATEPART(MONTH,DueDate) WHEN 10 THEN OrderQty END) AS October,
SUM(CASE DATEPART(MONTH,DueDate) WHEN 11 THEN OrderQty END) AS November,
SUM(CASE DATEPART(MONTH,DueDate) WHEN 12 THEN OrderQty END) AS December,
SUM(OrderQty) AS GrandTotal,
ProductID
FROM Production.WorkOrder
GROUP BY GROUPING SETS(
(DATEPART(YEAR, DueDate), ProductID),
(DATEPART(YEAR, DueDate)),
()
);
I have a report which looks for orders during a given date range... It returns the DateName from the report to give me mondays, it then gives me times from the report, to give me 859 for 08:59 for example.. I then use a case on this report to do the following...
WHEN (DATENAME(DW,T1.DocDate)) = 'Monday' AND T1.DocTime >= '700' AND T1.DocTime <= '859' THEN '1 Monday 07:00-08:59'
What I want to achieve, is the count for "1 Monday 07:00-08:59" to be divided by 2 if there has been 2 mondays, divided by 3 if there has been 3 mondays etc... but I have to be able to have it divide by 3 mondays for example, but 2 wednesdays if the date is a tuesday...
The report currently gives a Total of all orders placed in a datetime grouped together but has no division to average for each day.
SELECT (DATENAME(DW, T1.DocDate)) AS Weekday,
T1.DocTime AS Time,
SUM(T1.DocTotal) AS Value,
CASE
WHEN (DATENAME(DW, T1.DocDate)) = 'Monday'
AND T1.DocTime >= '700'
AND T1.DocTime <= '859' THEN '1 Monday 07:00-08:59'
FROM ORDR T1
INNER JOIN OCRD T0 ON T0.CardCode = T1.CardCode
WHERE (T1.DocDate >= #Start
AND T1.DocDate <= #End)
AND T0.QryGroup20 = 'Y'
AND T1.Canceled = 'N'
GROUP BY T1.DocTime,
T1.DocDate;
I expect the report to count the mondays / tuesdays etc that occur between #START and #END to give me an average sale per day and time.Then be able to then somehow divide by the count of the defined days in the case statement. (I'll hopefully be doing this part in Crystal Reports) but if i can get the first part, I'll work on the second half.
Just cross join the DW_Count subquery, which returns the count of every weekday in your orders range. Then you can count your avg for each weekday
SELECT (DATENAME(DW, T1.DocDate)) AS Weekday,
T1.DocTime AS Time,
SUM(T1.DocTotal) AS Value,
SUM(T1.DocTotal)/(CASE WHEN DATENAME(DW, T1.DocDate) = 'Monday' then DW_Count.MonCount
WHEN DATENAME(DW, T1.DocDate) = 'Tuesday' then DW_Count.TueCount
WHEN DATENAME(DW, T1.DocDate) = 'Wednesday' then DW_Count.WedCount
WHEN DATENAME(DW, T1.DocDate) = 'Thursday' then DW_Count.ThuCount
WHEN DATENAME(DW, T1.DocDate) = 'Friday' then DW_Count.FriCount
WHEN DATENAME(DW, T1.DocDate) = 'Saturday' then DW_Count.SatCount
WHEN DATENAME(DW, T1.DocDate) = 'Sunday' then DW_Count.SunCount) AS AvgValue
CASE
WHEN (DATENAME(DW, T1.DocDate)) = 'Monday'
AND T1.DocTime >= '700'
AND T1.DocTime <= '859' THEN '1 Monday 07:00-08:59'
FROM ORDR T1
INNER JOIN OCRD T0 ON T0.CardCode = T1.CardCode
CROSS JOIN (select sum(case when DATENAME(DW, DW_Count.DateValue) = 'Monday' then 1 else 0 end) as MonCount,
sum(case when DATENAME(DW, DW_Count.DateValue) = 'Tuesday' then 1 else 0 end) as TueCount,
sum(case when DATENAME(DW, DW_Count.DateValue) = 'Wednesday' then 1 else 0 end) as WedCount,
sum(case when DATENAME(DW, DW_Count.DateValue) = 'Thursday' then 1 else 0 end) as ThuCount,
sum(case when DATENAME(DW, DW_Count.DateValue) = 'Friday' then 1 else 0 end) as FriCount,
sum(case when DATENAME(DW, DW_Count.DateValue) = 'Saturday' then 1 else 0 end) as SatCount,
sum(case when DATENAME(DW, DW_Count.DateValue) = 'Sunday' then 1 else 0 end) as SunCount
from (select distinct DocDate from ORDR where (T1.DocDate >= #Start AND T1.DocDate <= #End))) AS DW_Count
WHERE (T1.DocDate >= #Start
AND T1.DocDate <= #End)
AND T0.QryGroup20 = 'Y'
AND T1.Canceled = 'N'
GROUP BY T1.DocTime,
T1.DocDate;
You can use the below logic-
For MSSQL
DECLARE #DT1 DATE = '20190802'
DECLARE #DT2 DATE = '20190820'
DECLARE #SatCount INT = 0
WHILE #DT1<= #DT2
BEGIN
SET #SatCount = #SatCount + CASE WHEN DATEPART(WeekDay,#DT1) = 7 THEN 1 ELSE 0 END
SET #DT1 = DATEADD(DD,1,#DT1)
END
SELECT #SatCount
Just one more option-
DECLARE #DT1 DATE = '20190802',
#DT2 DATE = '20190920';
SELECT SUM(CASE WHEN DATEPART(WeekDay,Date) = 7 THEN 1 ELSE 0 END)
FROM
(
SELECT TOP (DATEDIFF(DAY, #DT1, #DT2) + 1)
Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, #DT1)
FROM sys.all_objects a
-- A System table just used for creating multiple rows.
CROSS JOIN sys.all_objects b
-- CROSS JOIN will create number of row = original number of row X original number of row.
)A
Can I find the date of a day that is on which dates the Saturdays and Sundays of a specific month fall? For e.g consider the month of JANUARY-2017. The following dates are weekend days:
7/1/2017 - Saturday
14/1/2017 - Saturday
21/1/2017 - Saturday
28/1/2017 - Saturday
1/1/2017 - Sunday
8/1/2017 - Sunday
15/1/2017 - Sunday
22/1/2017 - Sunday
29/1/2017 - Sunday
I want a SQL Server query for this such that when I pass in month and year as input, I should get back all the above dates (only dates of Saturday and Sunday) as output
I do not wish to use any user defined function and want to finish it in a single SELECT statement
Note: As already noted by another user in the comments, this query depends upon your server settings, namely DATEFIRST. If you need alterations to the query because of different settings, just tell me and I can change it around for you.
Using a CTE as dummy data...
/* Ignore this part...*/
WITH CTE AS
(
SELECT CAST('01/01/2017' AS DATE) AS [Date]
UNION ALL
SELECT DATEADD(DAY,1,[Date])
FROM CTE
WHERE DATE <= '12/31/2017'
)
/*Your actual SELECT statement would look like this, from your own table of course*/
SELECT
[Date]
,CASE DATEPART(dw,[Date])
WHEN 1 THEN 'Sunday'
WHEN 2 THEN 'Monday'
WHEN 3 THEN 'Tuesday'
WHEN 4 THEN 'Wednesday'
WHEN 5 THEN 'Thursday'
WHEN 6 THEN 'Friday'
WHEN 7 THEN 'Saturday'
END
FROM CTE
WHERE DATEPART(dw,[Date]) IN (1,7)
AND MONTH([Date]) = 12--<month>
AND YEAR([Date]) = 2017--<year>
OPTION (MAXRECURSION 0) -- You won't need this line if you're querying a real table
;
If running that works for you, then your real query would probably look something like this:
SELECT
[Date]
,CASE DATEPART(dw,[Date])
WHEN 1 THEN 'Sunday'
WHEN 2 THEN 'Monday'
WHEN 3 THEN 'Tuesday'
WHEN 4 THEN 'Wednesday'
WHEN 5 THEN 'Thursday'
WHEN 6 THEN 'Friday'
WHEN 7 THEN 'Saturday'
END
FROM < the table you want >
WHERE DATEPART(dw,[Date]) IN (1,7) -- Only Sundays and Saturdays
AND MONTH([Date]) = < the month you want >
AND YEAR([Date]) = < the year you want >
;
If you want to generate the data, then a CTE is the way to go. If you're passing parameters, it would look something like this:
DECLARE
#MONTH INT
,#YEAR INT
;
SET #MONTH = 1;
SET #YEAR = 2017;
WITH CTE AS
(
SELECT CAST(CAST(#MONTH AS VARCHAR(2)) + '/01/' + CAST(#YEAR AS VARCHAR(4)) AS [Date]) AS DATE
UNION ALL
SELECT DATEADD(DAY,1,[Date])
FROM CTE
WHERE DATE <= CAST(#MONTH AS VARCHAR(2)) +
CASE
WHEN #MONTH IN (9,4,6,11)
THEN '/30/'
WHEN #MONTH IN (1,3,5,7,8,10,12)
THEN '/31/'
WHEN #MONTH = 2 AND #YEAR/4.00 = #YEAR/4
THEN '/29/'
ELSE '/28/'
END
+ CAST(#YEAR AS VARCHAR(4))
)
SELECT
[Date]
,CASE DATEPART(dw,[Date])
WHEN 1 THEN 'Sunday'
WHEN 2 THEN 'Monday'
WHEN 3 THEN 'Tuesday'
WHEN 4 THEN 'Wednesday'
WHEN 5 THEN 'Thursday'
WHEN 6 THEN 'Friday'
WHEN 7 THEN 'Saturday'
END
FROM CTE
WHERE DATEPART(dw,[Date]) IN (1,7)
OPTION (MAXRECURSION 0)
;
Please try this one.
DECLARE #Year AS INT=2017,
#Month AS INT=3,
#FirstDateOfYear DATETIME,
#LastDateOfYear DATETIME
SELECT #FirstDateOfYear = DATEADD(yyyy, #Year - 1900, 0)
SELECT #LastDateOfYear = DATEADD(yyyy, #Year - 1900 + 1, 0)
-- Creating Query to Prepare Year Data
;WITH cte AS (
SELECT 1 AS DayID,
#FirstDateOfYear AS FromDate,
DATENAME(dw, #FirstDateOfYear) AS Dayname
UNION ALL
SELECT cte.DayID + 1 AS DayID,
DATEADD(d, 1 ,cte.FromDate),
DATENAME(dw, DATEADD(d, 1 ,cte.FromDate)) AS Dayname
FROM cte
WHERE DATEADD(d,1,cte.FromDate) < #LastDateOfYear
)
SELECT FromDate AS Date, Dayname
FROM CTE
WHERE DayName IN ('Saturday','Sunday') and month(FromDate) = #Month
OPTION (MaxRecursion 370)
This should do the trick:
DECLARE #month date = '2017-01-01'
SET #month = dateadd(month, datediff(month, 0, #month), 0)
;WITH CTE as
(
SELECT 0 x
FROM (values(1),(1),(1),(1),(1),(1)) x(n)
),
CTE2 as
(
SELECT
top(day(eomonth(#month)))
-- use this syntax for sqlserver 2008
-- top(datediff(d, #month,dateadd(month,1,#month)))
cast(dateadd(d, row_number()over(order by(select 1))-1,#month) as date) cDate
FROM CTE CROSS JOIN CTE C2
)
SELECT
cDate,
datename(weekday, cDate) Weekday
FROM CTE2
WHERE
datediff(d,0,cDate)%7 > 4
Fiddle
From https://www.sqlservercentral.com/articles/finding-the-correct-weekday-regardless-of-datefirst, you simply:
(DATEPART(dw, #your_date) + ##DATEFIRST) % 7 NOT BETWEEN 2 AND 6
As requested, single select, language neutral, dateFirst neutral, almost SQL version neutral:
declare #OneDate datetime = '28/01/2017'; -- Any date from the target month/year
select MyDate -- raw date or ...
-- convert(varchar, MyDate, 103) + ' - ' + dateName(dw, MyDate) -- as Sample
as WeekEndDate
from (
select dateAdd(dd, number, dateAdd(mm, dateDiff(mm, 0, #OneDate), 0)) as MyDate
from master..spt_values
where type = 'P' and number < 31
) j
where 1 + (datePart(dw, MyDate) + ##DATEFIRST + 5) % 7 in (6, 7)
and month(MyDate) = month(#OneDate)
-- order by 1 + (datePart(dw, MyDate) + ##DATEFIRST + 5) % 7, MyDate -- as Sample
;
Another way to solve this problem as follow -
DECLARE #MONTH INT,#YEAR INT
SET #MONTH = 1;
SET #YEAR = 2017;
Declare #StartDate date =CAST(CAST(#MONTH AS VARCHAR(2)) + '/01/' + CAST(#YEAR AS VARCHAR(4)) AS [Date]), #EndDate date
Set #EndDate = EOMONTH(#StartDate)
Declare #Temp table (DateOfDay date, DaysName varchar(50))
While(#StartDate <= #EndDate)
Begin
Insert into #Temp
SELECT #StartDate DateOfMonth,
case when DATENAME(DW, #StartDate) = 'Saturday' then DATENAME(DW, #StartDate)
when DATENAME(DW, #StartDate) = 'Sunday' then DATENAME(DW, #StartDate)
end DaysName
set #StartDate = DATEADD(d,1,#StartDate)
End
select * from #Temp where DaysName is not null order by DaysName, DateOfDay
Can't you do something like this?
SELECT DATENAME(dw,'10/11/2016') AS DATE
WHERE DATE CONTAINS('Saturday') OR DATE CONTAINS('SUNDAY')
and instead of '10/11/2016' you only have to figure out how to generate all the dates in a month/year?
I have a table consisting of an creation date, an id of the item created, and other unimportant information. What I want to do is write a query that sums up items created year to date by week for a given date range. So if I have this table:
ID creationdate
-- ------------
1 1/1/2015
2 1/2/2015
3 1/3/2015
4 1/3/2015
5 1/3/2015
6 1/5/2015
7 1/6/2015
And if I were to query for the date range of 12/29/2014 through 1/11/2015, I want to see these results:
weekof count
------ -----
12/29/2014 5
1/05/2015 7
Is there any way to achieve this?
One way to calculate cumulative values on a table is to create a self join and connect the joined fields with the >= comparison operator.
It appears from you question that your week starts on a Monday. Therefore, you will also need to calculate the immediate preceding Monday for each row in your table. In my solution, I calculated the name of the day using DATENAME and then subtract from the creation date the number of days the creation date is past Monday.
Finally, I formatted the date using the FORMAT function.
CREATE TABLE [dbo].[DateTest] ---Create Test Table DateTest
(
[ID] [int] NULL,
[CreationDate] [datetime] NULL
)
GO
---Insert Values
INSERT INTO
DateTest
VALUES
('1','1/1/2015'),
('2','1/2/2015'),
('3','1/3/2015'),
('4','1/3/2015'),
('5','1/3/2015'),
('6','1/5/2015'),
('7','1/6/2015')
GO
---Perform the calculation
SELECT
FORMAT(t1.StartOfWeek, 'd', 'en-US') as StartOfWeek, ----Render date as mm/dd/yyyy
SUM(t2.CountForWeek) as CumulativeRecordCount
FROM
(
SELECT
(CASE --Determine the most recent preceding Monday, because Monday is defined as the beginning of the week
WHEN DATENAME(dw,CreationDate) = 'Sunday' THEN CreationDate-6
WHEN DATENAME(dw,CreationDate) = 'Saturday' THEN CreationDate-5
WHEN DATENAME(dw,CreationDate) = 'Friday' THEN CreationDate-4
WHEN DATENAME(dw,CreationDate) = 'Thursday' THEN CreationDate-3
WHEN DATENAME(dw,CreationDate) = 'Wednesday' THEN CreationDate-2
WHEN DATENAME(dw,CreationDate) = 'Tuesday' THEN CreationDate-1
ELSE CreationDate
END) AS StartOfWeek,
COUNT(id) AS CountForWeek
FROM
DateTest
GROUP BY
(CASE --Determine the most recent preceding Monday, because Monday is defined as the beginning of the week
WHEN DATENAME(dw,CreationDate) = 'Sunday' THEN CreationDate-6
WHEN DATENAME(dw,CreationDate) = 'Saturday' THEN CreationDate-5
WHEN DATENAME(dw,CreationDate) = 'Friday' THEN CreationDate-4
WHEN DATENAME(dw,CreationDate) = 'Thursday' THEN CreationDate-3
WHEN DATENAME(dw,CreationDate) = 'Wednesday' THEN CreationDate-2
WHEN DATENAME(dw,CreationDate) = 'Tuesday' THEN CreationDate-1
ELSE CreationDate
END)
) AS t1
INNER JOIN --Self Join Table
(
SELECT
(CASE --Determine the most recent preceding Monday, because Monday is defined as the beginning of the week
WHEN DATENAME(dw,CreationDate) = 'Sunday' THEN CreationDate-6
WHEN DATENAME(dw,CreationDate) = 'Saturday' THEN CreationDate-5
WHEN DATENAME(dw,CreationDate) = 'Friday' THEN CreationDate-4
WHEN DATENAME(dw,CreationDate) = 'Thursday' THEN CreationDate-3
WHEN DATENAME(dw,CreationDate) = 'Wednesday' THEN CreationDate-2
WHEN DATENAME(dw,CreationDate) = 'Tuesday' THEN CreationDate-1
ELSE CreationDate
END) AS StartOfWeek,
COUNT(id) AS CountForWeek
FROM
DateTest
GROUP BY
(CASE --Determine the most recent preceding Monday, because Monday is defined as the beginning of the week
WHEN DATENAME(dw,CreationDate) = 'Sunday' THEN CreationDate-6
WHEN DATENAME(dw,CreationDate) = 'Saturday' THEN CreationDate-5
WHEN DATENAME(dw,CreationDate) = 'Friday' THEN CreationDate-4
WHEN DATENAME(dw,CreationDate) = 'Thursday' THEN CreationDate-3
WHEN DATENAME(dw,CreationDate) = 'Wednesday' THEN CreationDate-2
WHEN DATENAME(dw,CreationDate) = 'Tuesday' THEN CreationDate-1
ELSE CreationDate
END)
) AS t2
ON
t1.StartOfWeek >= t2.StartOfWeek --- join t2.startofweek to all t1.startofweek dates greater than or equal to t2.startofweek
GROUP BY
t1.StartOfWeek
OUTPUT
StartOfWeek CumulativeRecordCount
------------- ---------------------
12/29/2014 5
1/5/2015 7
Okay so I have made a report calculating how many contracts are funded in each month within the year 2014.
So Now I have to calculate the total for all the contracts that are in SERVICE ONLY.
What I mean by this is I have a table called tlkOrigDept. Within that table I have this
Table tlkOrigDept
orig_dept_id Orig_Dept_Name
1 Sales
2 Service
3 F&I
4 Other
5 Direct Marketing
So I have to get all the funded contracts ONLY that from SERVICE which is 'orig_dept_id' = 2 So this is my Query but the problem I see is in my where clause. Because when I change the orig_dept_Id to 3 it works but not for 2. It just shows blank and not an error message.
The user inputs a #Begin_date and #End_Date the User than picks a company which is #Program. The user should see ALL the FUNDED Contracts for each month that are from SERVICE ONLY.
I either see a problem in the SELECT Statement or my WHERE Clause
Here is my Query
[code="sql"]
Alter Proc spGetAdminServiceYTD
(#Begin_Date DATETIME,
#End_Date DATETIME,
#program int=null) As
Declare #year int
Set #year = 2014
Declare #orig_dept_ID Int
Set #orig_dept_ID = 2
Begin
SELECT d.name, a.dealer_code, b.last_name, b.city, b.state, b.phone,e.orig_dept_name
, COUNT(CASE WHEN MONTH(c.orig_dept_id) = 1 THEN 1 ELSE NULL END) January
, COUNT(CASE WHEN MONTH(c.orig_dept_id) = 2 THEN 1 ELSE NULL END) Feburary
, COUNT(CASE WHEN MONTH(c.Funded_date) = 3 THEN 1 ELSE NULL END) March
, COUNT(CASE WHEN MONTH(c.Funded_date) = 4 THEN 1 ELSE NULL END) April
, COUNT(CASE WHEN MONTH(c.Funded_date) = 5 THEN 1 ELSE NULL END) May
, COUNT(CASE WHEN MONTH(c.Funded_date) = 6 THEN 1 ELSE NULL END) June
, COUNT(CASE WHEN MONTH(c.Funded_date) = 7 THEN 1 ELSE NULL END) July
, COUNT(CASE WHEN MONTH(c.Funded_date) = 8 THEN 1 ELSE NULL END) August
, COUNT(CASE WHEN MONTH(c.Funded_date) = 9 THEN 1 ELSE NULL END) September
, COUNT(CASE WHEN MONTH(c.Funded_date) = 10 THEN 1 ELSE NULL END) October
, COUNT(CASE WHEN MONTH(c.Funded_date) = 11 THEN 1 ELSE NULL END) November
, COUNT(CASE WHEN MONTH(c.Funded_date) = 12 THEN 1 ELSE NULL END) December
, count(1) As YTD
FROM tdealer a
JOIN tContact b ON a.contact_id = b.contact_id
JOIN tContract c ON a.dealer_id = c.dealer_id
JOIN tCompany d ON c.company_id = d.company
JOIN tlkOrigDept E ON c.orig_dept_id = e.orig_dept_id
WHERE c.orig_dept_id = 2
And d.company_id = #program
AND c.Funded_date >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-5, 0)
And YEAR(c.Funded_date) = #Year
And c.Funded_date < DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, 0)
And (c.funded_date) between #Begin_Date And #End_Date
GROUP BY
d.name,
a.dealer_code,
b.last_name,
b.city,
b.state,
b.phone,
MONTH(c.funded_date),
Month(e.orig_dept_name),
e.orig_dept_name
end
exec spGetAdminServiceYTD '01/01/2014', '05/30/2014', '47'