I want to group by results of sales by YEAR-MONTH. My current query which does the results looks like :
SELECT Cast(Year(s.datekey) AS VARCHAR(4)) + '-'
+ Cast(Month(s.datekey) AS VARCHAR(2)) AS Mjesec,
e.employeekey,
Sum(s.totalcost) AS SalesAmount
FROM factsales s
INNER JOIN dimstore st
ON s.storekey = st.storekey
INNER JOIN dimemployee e
ON e.employeekey = st.storemanager
WHERE s.datekey BETWEEN '2007-01-01' AND '2007-01-05'
GROUP BY e.employeekey,
Cast(Year(s.datekey) AS VARCHAR(4)) + '-'
+ Cast(Month(s.datekey) AS VARCHAR(2))
ORDER BY employeekey
I am wondering if there are any other better and more elegant way to achieve same results? Perhaps, more friendly format for DateTime in c#?
Much more efficient to strip time by using date math than converting to a string. Also much more efficient to leave the particular string formatting to the end (or better yet, doing it in C# using Format()).
;WITH c AS
(
SELECT m = DATEADD(MONTH, DATEDIFF(MONTH, 0, s.datekey), 0),
e.employeekey, s.totalcost
FROM dbo.factsales AS s
INNER JOIN dbo.dimstore AS st
ON s.storekey = st.storekey
INNER JOIN dimemployee AS e
ON e.employeekey = st.storemanager
WHERE s.datekey >= '20070101' AND s.datekey < '20070106'
),
d AS
(
SELECT m, employeekey, SalesAmount = SUM(totalcost)
FROM c
GROUP BY m, employeekey
)
SELECT
Mjesec = CONVERT(CHAR(7), m, 120),
employeekey,
SalesAmount
FROM d
ORDER BY employeekey;
If you can do the formatting in your app, then you can collapse this to:
;WITH c AS
(
SELECT m = DATEADD(MONTH, DATEDIFF(MONTH, 0, s.datekey), 0),
e.employeekey, s.totalcost
FROM dbo.factsales AS s
INNER JOIN dbo.dimstore AS st
ON s.storekey = st.storekey
INNER JOIN dimemployee AS e
ON e.employeekey = st.storemanager
WHERE s.datekey >= '20070101' AND s.datekey < '20070106'
)
SELECT Mjesec = m, employeekey, SalesAmount = SUM(totalcost)
FROM c
GROUP BY m, employeekey
ORDER BY employeekey;
Or even:
SELECT Mjesec = DATEADD(MONTH, DATEDIFF(MONTH, 0, s.datekey), 0),
e.employeekey, s.totalcost
FROM dbo.factsales AS s
INNER JOIN dbo.dimstore AS st
ON s.storekey = st.storekey
INNER JOIN dimemployee AS e
ON e.employeekey = st.storemanager
WHERE s.datekey >= '20070101' AND s.datekey < '20070106'
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, s.datekey, 0), 0), e.employeekey
ORDER BY employeekey;
Do:
SELECT CONVERT(CHAR(7),s.DateKey,120) AS Mjesec....
FROM ....
GROUP BY CONVERT(CHAR(7),s.DateKey,120)....
ORDER BY EmployeeKey
Related
I have this query
SELECT
C.RazonSocial AS 'Contratista',
C.Cuit,
CTO.Numero AS 'Contrato',
S.Codigo as 'Codigo Sociedad',
S.Descripcion AS 'Sociedad',
CTO.FechaInicio AS 'Fecha Inicio',
CTO.VigenciaHasta AS 'Fecha Fin',
CER.FechaInicio AS 'Fecha Inicio Exepcion',
CER.FechaFin AS 'Fecha Fin Excepcion',
CPPC.Porcentaje
FROM
ContratosExcepcionesRetencion AS CER
INNER JOIN
Contratistas AS C ON C.Id = CER.ContratistaId
INNER JOIN
Contratos AS CTO ON CTO.ContratistaId = C.Id
INNER JOIN
Sociedads AS S ON S.Id = CTO.SociedadId
INNER JOIN
ContratoPeriodoPorcentajeCumplimiento AS CPPC ON CPPC.ContratoId = CTO.Id
INNER JOIN
Periodos AS PER ON PER.Id = CPPC.PeriodoId
WHERE
PER.Fecha < DATEADD(month, -2, GETDATE()) AND
PER.Fecha > DATEADD(month, -5, GETDATE()) AND
CTO.Numero = '4900074911'
GROUP BY
C.RazonSocial,
C.Cuit,
CTO.Numero,
S.Codigo,
S.Descripcion,
CTO.FechaInicio,
CTO.VigenciaHasta,
CER.FechaInicio,
CER.FechaFin,
CPPC.Porcentaje
With the following results:
{]1
but I want the following result:
Thank you in advance
I have 2 result sets from different CTE selects, and i need to take out the value of 2 columns in first table from the value of 2 columns in second table.
Query description: In first result i find count of total new customers, and in the second result i get the customers that have any sales ( joining the factsales table ) and what i need is to find the count of new customers that dont have any invoices ( revenue made ). So from my logic that will mean the total number of customers from the first result - the total number of customers that have any revenue ( meaning they can be found in the factSales table ). So the count of customers without any revenue are found in customer table, but arent in factsales table. I hope this simplifies my issue and expectations. Thanks for the help provided.
use dwh01;
-- Total number of new customers
with cte1 as(
SELECT
d.[Year],
d.[month],
case when c.branchid = '1080' then c.customerid end as New_Customers_Per_Month_1080,
case when c.branchid = '1081' then c.customerid end as New_Customers_Per_Month_1081
FROM [dwh01].[live].[DimCustomer] c
inner join live.DimDate d -- Date join
on d.DayDate = c.Createdate
where d.DayDate >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-12, 0) and d.DayDate <= DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1) and c.IsActive = 'Y'
)
select
c.[Year],
c.[month],
count(distinct c.New_Customers_Per_Month_1080) as New_Customers_1080,
count(distinct c.New_Customers_Per_Month_1081) as New_Customers_1081
from cte1 c
group by c.[Year], c.[month]
order by c.[year] asc, c.[month] asc
;
-- new customers that have any revenue
with cte1 as(
SELECT
d.[Year],
d.[month],
case when c.branchid = '1080' then c.customerid end as New_Customers_Per_Month_1080,
case when c.branchid = '1081' then c.customerid end as New_Customers_Per_Month_1081
FROM live.FactSales fs
inner join [live].[DimCustomer] c
on fs.customerkey = c.CustomerKey
inner join live.DimDate d -- Date join
on d.DayDate = c.Createdate
where d.DayDate >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-12, 0) and d.DayDate <= DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1) and c.IsActive = 'Y'
)
select
c.[Year],
c.[month],
count(distinct c.New_Customers_Per_Month_1080) as New_Customers_1080,
count(distinct c.New_Customers_Per_Month_1081) as New_Customers_1081
from cte1 c
group by c.[Year], c.[month]
order by c.[year] asc, c.[month] asc
Result from first table:
Expected result:
You can define any number of common table expression sequentially. Here I have created two cte named cte1 and cte2 first then joined both with [year] and [month] column and used group by clause to get what you want.
with cte1 as(
SELECT
d.[Year],
d.[month],
case when c.branchid = '1080' then c.customerid end as New_Customers_Per_Month_1080,
case when c.branchid = '1081' then c.customerid end as New_Customers_Per_Month_1081
FROM [dwh01].[live].[DimCustomer] c
inner join live.DimDate d -- Date join
on d.DayDate = c.Createdate
where d.DayDate >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-12, 0) and d.DayDate <= DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1) and c.IsActive = 'Y'
) , cte2 as(
SELECT
d.[Year],
d.[month],
case when c.branchid = '1080' then c.customerid end as New_Customers_Per_Month_1080,
case when c.branchid = '1081' then c.customerid end as New_Customers_Per_Month_1081
FROM live.FactSales fs
inner join [live].[DimCustomer] c
on fs.customerkey <> c.CustomerKey
inner join live.DimDate d -- Date join
on d.DayDate = c.Createdate
where d.DayDate >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-12, 0) and d.DayDate <= DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1) and c.IsActive = 'Y'
)
select
c.[Year],
c.[month],
(count(distinct c.New_Customers_Per_Month_1080)-count(distinct c2.New_Customers_Per_Month_1080)) as New_Customers_1080,
(count(distinct c.New_Customers_Per_Month_1081)-count(distinct c2.New_Customers_Per_Month_1081)) as New_Customers_1081
from cte1 c inner join cte2 c2
on c.[year]=c2.[year] and c.[month]=c2.[month]
group by c.[Year], c.[month]
order by c.[year] asc, c.[month] asc
You can have two CTEs defined first and later you can join them, as given below:
-- Total number of new customers
;with cte1 as(
SELECT
d.[Year],
d.[month],
case when c.branchid = '1080' then c.customerid end as New_Customers_Per_Month_1080,
case when c.branchid = '1081' then c.customerid end as New_Customers_Per_Month_1081
FROM [dwh01].[live].[DimCustomer] c
inner join live.DimDate d -- Date join
on d.DayDate = c.Createdate
where d.DayDate >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-12, 0) and d.DayDate <= DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1) and c.IsActive = 'Y'
) , cte2 as(
SELECT
d.[Year],
d.[month],
case when c.branchid = '1080' then c.customerid end as New_Customers_Per_Month_1080,
case when c.branchid = '1081' then c.customerid end as New_Customers_Per_Month_1081
FROM live.FactSales fs
inner join [live].[DimCustomer] c
on fs.customerkey <> c.CustomerKey
inner join live.DimDate d -- Date join
on d.DayDate = c.Createdate
where d.DayDate >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-12, 0) and d.DayDate <= DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1) and c.IsActive = 'Y'
)
SELECT cte1.Year
, cte1.Month
, (cte1.New_Customers_Per_Month_1080 - cte2.New_Customers_Per_Month_1080) AS New_Customers_1080
,, (cte1.New_Customers_Per_Month_1081 - cte2.New_Customers_Per_Month_1081) AS New_Customers_1081
FROM cte1
INNER JOIN cte2
ON cte2.Year = cte1.Year AND cte2.Month = cte1.Month
I want Group by customer and sum CuryDocBal and return the top 15 customers after grouping
My current code only returns 15 rows. For example, I want Morton Salt Company's totals to be summed and represent 1 row.
select top 15 a.Name ,d.CuryDocBal
from
ARDoc d
inner join
[AR_Balances] b
on d.CpnyID = b.CpnyID
inner join [SIVSYS].[dbo].[Company] c
on b.CpnyID = c.CpnyID
inner join Customer a
on d.CustId = a.Custid
--DocType = 'IN'
where
d.dueDate BETWEEN dateadd(day, -21, cast(getdate() as date)) and dateadd(day, 7, cast(getdate() as date))
and CuryDocBal <> 0
group by a.Name ,
d.CuryDocBal
order by d.CuryDocBal desc;
you need sum()
select top 15 a.Name, d.DueDate, sum(d.CuryDocBal) curyDocBal ,d.RefNbr, d.BatNbr,
b.CpnyID
,c.CpnyName
from
ARDoc d
inner join
[AR_Balances] b
on d.CpnyID = b.CpnyID
inner join [SIVSYS].[dbo].[Company] c
on b.CpnyID = c.CpnyID
inner join Customer a
on d.CustId = a.Custid
--DocType = 'IN'
where
d.dueDate BETWEEN dateadd(day, -21, cast(getdate() as date)) and dateadd(day, 7, cast(getdate() as date))
-- and d.dueDate < dateadd(day, 7, cast(getdate() as date))
-- (DueDate BETWEEN GETDATE() AND DATEADD(DAY, +7, GETDATE())
--or
--DueDate BETWEEN DATEADD(day,-21, GETDATE()) AND GETDATE())
and CuryDocBal <> 0
group by a.Name, d.DueDate,
d.CuryDocBal, b.CpnyID
,c.CpnyName, d.RefNbr, d.BatNbr
order by d.CuryDocBal desc;
Remove CuryDocBal from the group by and sum it instead.
select top 15
a.Name,
TotalCuryDocBal = sum(d.CuryDocBal)
from ARDoc d
inner join [AR_Balances] b on d.CpnyID = b.CpnyID
inner join [SIVSYS].[dbo].[Company] c on b.CpnyID = c.CpnyID
inner join Customer a on d.CustId = a.Custid
--DocType = 'IN'
where
d.dueDate BETWEEN dateadd(day, -21, cast(getdate() as date)) and dateadd(day, 7, cast(getdate() as date))
and CuryDocBal <> 0
group by a.Name
order by TotalCuryDocBal desc;
I have this stored procedure...
SELECT
LTRIM(RTRIM([OF].OF_DISPLAYNAME)) AS [Officer_Name],
LTRIM(RTRIM([OF].OF_PIN)) AS Officer_Pin,
LTRIM(RTRIM([TO].TO_ACTIVITY)) AS Template_Site,
AC.AC_NAME AS Site_Name,
ZN.ZN_MANAGER AS Site_Manager,
AR.AR_DESCRIPTION AS Scheduler,
CONVERT(VARCHAR(10), #WeekCommencing, 6) AS [Week_Commencing],
CONVERT(VARCHAR(10), [OF].OF_DOL, 6) AS Leave_Date,
CAST((SELECT
(ISNULL(SUM(RO.RO_SHIFT_LENGTH - RO_BREAK_LENGTH), 0.0)/60.0)
FROM
RoleCall.dbo.ROSTER AS RO WITH(NOLOCK)
WHERE
RO.RO_OFFICER = [OF].OF_PIN
AND RO.RO_SHIFT_START BETWEEN #WeekCommencing AND #WeekEnding
AND RO.RO_STATUS IN ('COMP', 'CONF', 'TODO')
) AS DECIMAL(11,2)) AS HoursSum,
RSWH.dbo.RSWHF_GetMarker([OF].OF_PIN, #WeekCommencing, #WeekEnding) AS Marker,
CONVERT(VARCHAR(10), (SELECT MAX(RO.RO_SHIFT_START)
FROM RoleCall.dbo.ROSTER AS RO WITH(NOLOCK)
WHERE RO.RO_OFFICER = [OF].OF_PIN
AND RO.RO_SHIFT_START < GETDATE()
AND RO.RO_STATUS IN ('COMP', 'CONF', 'TODO')
), 6) AS Last_Worked_Shift,
CONVERT(VARCHAR(10), (SELECT TOP 1
HC.Effective_Date
FROM HR.dbo.HRST_Contract AS HC WITH(NOLOCK)
WHERE
HC.Of_Pin = [OF].OF_PIN
AND HC.SD_Contract = 1
ORDER BY
Effective_Date DESC
), 6) AS Contract_Sent_Date,
CONVERT(VARCHAR(10),
(
SELECT TOP 1
RO.RO_SHIFT_START
FROM
Rolecall.dbo.Roster AS RO WITH(NOLOCK)
WHERE
RO.RO_Activity = 'ENDASSIG'
AND RO.RO_STATUS <> 'CANC'
AND RO.RO_OFFICER =[OF].OF_PIN
AND RO.RO_SHIFT_START < #WeekEnding
ORDER BY
RO.RO_SHIFT_START DESC
), 6) AS Ass_End_Date,
ISNULL(CreatedBy, '') AS Checked_By,
---ISSUE IS OCCURRING HERE----
(
SELECT
SUM(a.[Value*NumofActivity]) + max(b.NumOfHoursWorkedInTheLast12Weeks) AS [TotalHoursWorkedInTheLast12Weeks],Markers
FROM
(
SELECT
RO_OFFICER [RO_OFFICER],RO_ACTIVITY , COUNT(RO_ACTIVITY)*Value as [Value*NumofActivity]
FROM
RoleCall.dbo.ROSTER as ro inner join [RSWH].DBO.[RSWHT_Hours_Assigned_To_Markers_LookUp] AS MR on RO_ACTIVITY = MR.MARKER
WHERE
ro_officer = [OF].OF_PIN
AND RO_STATUS = 'INFO'
AND RO_SHIFT_START between DATEADD(week, -12, GETDATE()) AND GETDATE()
GROUP BY
RO_OFFICER,RO_ACTIVITY,Value) a
JOIN
(
SELECT
RO_OFFICER [RO_OFFICER] ,(ISNULL(SUM(RO_SHIFT_LENGTH - RO_BREAK_LENGTH), 0.0)/60.0)as [NumOfHoursWorkedInTheLast12Weeks],RSWH.dbo.RSWHF_GetMarker(RO_OFFICER, DATEADD(week, -12, GETDATE()), GETDATE()) AS Markers
FROM
ROLECALL.DBO.ROSTER as ro inner join [RSWH].DBO.[RSWHT_Hours_Assigned_To_Markers_LookUp] AS MR on RO_ACTIVITY = MR.MARKER
WHERE
RO_SHIFT_START >= DATEADD(week, -12, GETDATE()) AND RO_SHIFT_START <= GETDATE()
AND RO.RO_STATUS = 'INFO'
AND RO_OFFICER = [OF].OF_PIN
GROUP BY
RO_OFFICER
) b on a.RO_OFFICER = b.RO_OFFICER
GROUP BY A.RO_OFFICER,b.NumOfHoursWorkedInTheLast12Weeks,Markers)
FROM
RoleCall.dbo.OFFICER AS [OF] WITH (NOLOCK)
LEFT JOIN RoleCall.dbo.TEMPLATE AS [TO] WITH (NOLOCK) ON [TO].TO_PIN = [OF].OF_PIN AND [TO].TO_TYPE COLLATE Latin1_General_CS_AS = 'M'
LEFT JOIN RoleCall.dbo.ACTIVITY AS AC WITH (NOLOCK) ON AC.AC_PIN = [TO].TO_ACTIVITY
LEFT JOIN RoleCall.dbo.ZONE AS ZN WITH (NOLOCK) ON ZN.ZN_ZONE = AC.AC_ZONE
LEFT JOIN RoleCall.dbo.AREA AS AR WITH (NOLOCK) ON AR.AR_AREA = AC.AC_AREA
LEFT JOIN Appollo.ACMS.dbo.ACSMT_Checked_Officer AS CO WITH (NOLOCK) ON CO.OfficerPin = [OF].OF_PIN AND WeekCommencing BETWEEN #WeekCommencing AND #WeekEnding
WHERE
[OF].OF_PAYROLL_NO IN ('W', 'S')
AND [OF].OF_SKILLS = #Of_Skills --
AND (#Of_Skills = 'R' OR AC.AC_PARENT IN ('9947', '9133'))
AND ([OF].OF_DOL IS NULL OR [OF].OF_DOL > #WeekCommencing)
AND [OF].OF_RANK <> 'PT'
AND [OF].OF_RANK <> 'LW'
AND EXISTS (
SELECT
TOP 1 Of_Pin
FROM
HR.dbo.HRST_Contract AS HC WITH(NOLOCK)
WHERE
Of_Pin = [OF].OF_PIN
AND ISNULL(SD_Contract, 0) = 1
)
AND (
SELECT
ISNULL(SUM(RO.RO_SHIFT_LENGTH - RO_BREAK_LENGTH), 0.0)
FROM
RoleCall.dbo.ROSTER AS RO WITH(NOLOCK)
WHERE
RO.RO_OFFICER = [OF].OF_PIN
AND RO.RO_SHIFT_START BETWEEN #WeekCommencing AND #WeekEnding
AND (RO.RO_STATUS IN ('COMP', 'CONF', 'TODO') OR (RO_Activity ='LEAVE' AND RO_STATUS <> 'CANC'))
) < 420.0
AND (ISNULL(CreatedBy, '') = '' OR #UncheckedOfficersOnly = 0)
ORDER BY
Officer_Name,
Officer_Pin
The issue is I need to return the three columns which I'm trying to sum. I haven't got much experience in SQL and I was wondering if anyone has any suggestions or pointers for this to be done.
Thank you
The code below (and numerous codes like it) continues to return blanks.
Basically, if LaborCode = '01 - SC' then it should sort by JobSite, LaborCode, and Schedule (the exact date)
If it's NOT 01 - SC, it should sort by JobSite, LaborCode, and DayNo (the day of the week)
Select Distinct Agreements.AgrmntID, Agreements.Description, Agreements.Status,
JobSites.SiteName, JobSites.Address2, JobSites.City, Customers.CustName,
Customers.CompanyName, LaborCodeTypes.RepairCode As LaborCode, Schedule = Case
LaborCodeTypes.RepairCode
When '01 - SC' Then Left(Convert(varchar,AgreementSchedules.SchedDate,110),
10) Else DateName(dw, AgreementSchedules.SchedDate)
End, Employees1.EmpName As Vendor, Employees.EmpName As [Area Manager],
DatePart(dw, AgreementSchedules.SchedDate) As DayNo
From Agreements Inner Join
Customers On Agreements.CustID = Customers.CustID Inner Join
AgreementSchedules On Agreements.AgrmntID = AgreementSchedules.AgrmntID
Inner Join
JobSites On Agreements.CustSiteID = JobSites.CustSiteID Left Outer Join
LaborCodeTypes On AgreementSchedules.RepairID = LaborCodeTypes.RepairID
Left Outer Join
Employees On AgreementSchedules.FormanEmpID = Employees.EmployeeID Left Join
WorkOrderSchedules On WorkOrderSchedules.ScheduleID =
AgreementSchedules.ScheduleID And AgreementSchedules.ScheduleID =
WorkOrderSchedules.ScheduleID Left Join
WorkOrderScheduleTechs On WorkOrderSchedules.ScheduleID =
WorkOrderScheduleTechs.ScheduleID Left Join
Employees Employees1 On WorkOrderScheduleTechs.EmployeeID =
Employees1.EmployeeID
Where Agreements.Status = 2 And LaborCodeTypes.RepairCode <> 'Vendor Bill' And
Month(AgreementSchedules.SchedDate) = Month(GetDate())
Order By Case
When [LaborCodeTypes.RepairCode] In ('01 - SC') Then JobSites.SiteName +
LaborCodeTypes.RepairCode + Schedule
Else JobSites.SiteName + LaborCodeTypes.RepairCode + DayNo End
Thank you for your help!!
Try this:
ORDER BY JobSites.SiteName,
LaborCodeTypes.RepairCode,
CASE WHEN LaborCodeTypes.RepairCode IN ('01 - SC') THEN Schedule ELSE DayNo END
Okay, in SQL Server:
CREATE PROCEDURE dbo.Agreements_GetList
AS
BEGIN
SET NOCOUNT ON;
SELECT DISTINCT
a.AgrmntID,
a.Description,
a.Status,
js.SiteName,
js.Address2,
js.City,
c.CustName,
c.CompanyName,
LaborCode = lct.RepairCode,
Schedule = CASE lct.RepairCode
WHEN '01 - SC' THEN CONVERT(CHAR(10), aSch.SchedDate, 110)
--------------------^^^ much better than LEFT and not specifying length
ELSE DATENAME(WEEKDAY, aSch.SchedDate) END,
Vendor = e2.EmpName,
[Area Manager] = e1.EmpName,
DayNo = CONVERT(CHAR(1), DATEPART(WEEKDAY, aSch.SchedDate))
--------^^^ this convert is important
FROM dbo.Agreements AS a
INNER JOIN dbo.Customers AS c
ON a.CustID = c.CustID
INNER JOIN dbo.AgreementSchedules AS aSch
ON a.AgrmntID = aSch.AgrmntID
INNER JOIN dbo.JobSites AS js
ON a.CustSiteID = js.CustSiteID
LEFT OUTER JOIN dbo.LaborCodeTypes AS lct
ON aSch.RepairID = lct.RepairID
LEFT OUTER JOIN dbo.Employees AS e1
ON aSch.FormanEmpID = e1.EmployeeID
LEFT OUTER JOIN dbo.WorkOrderSchedules AS w
ON w.ScheduleID = aSch.ScheduleID
LEFT OUTER JOIN dbo.WorkOrderScheduleTechs AS wt
ON w.ScheduleID = wt.ScheduleID
LEFT OUTER JOIN dbo.Employees AS e2
ON wt.EmployeeID = e2.EmployeeID
WHERE
a.Status = 2
AND lct.RepairCode <> 'Vendor Bill'
AND aSch.SchedDate >= DATEADD(MONTH, 0, DATEDIFF(MONTH, 0, GETDATE()))
AND aSch.SchedDate < DATEADD(MONTH, 1, DATEDIFF(MONTH, 0, GETDATE()))
ORDER BY
js.SiteName,
lct.RepairCode,
CASE WHEN lct.RepairCode = '01 - SC'
THEN js.SiteName ELSE DayNo END;
END
GO
Now I have absolutely no knowledge of your application, so you will have to figure out how to call a stored procedure from it instead of embedding SQL.