Aggregate function on an expression containing an aggregate or a subquery - sql

I'm getting an error
"Cannot perform an aggregate function on an expression containing an aggregate or a subquery"
which is this line:
,MIN(CASE WHEN DateCompleted IS NULL THEN MIN(DateReceived) ELSE '' END) AS Oldest_Claim
I'm not sure how to handle this because I can't include DateCompleted in the GROUP BY clause and get the results that I need. Thanks
DECLARE #StartDate smalldatetime = '1/1/2000'
DECLARE #EndDate smalldatetime = '3/13/2019'
SELECT
CASE
WHEN DischargeType = 'atb' THEN 'Ability to Benefit'
WHEN DischargeType = 'cls' THEN 'Closed School'
WHEN DischargeType = 'death' THEN 'Death'
WHEN DischargeType = 'dqs' THEN 'Disqualifying Status'
WHEN DischargeType = 'fraud' THEN 'Fraud'
WHEN DischargeType = 'id theft' THEN 'ID Theft'
WHEN DischargeType = 'ineligible borrower' THEN 'Ineligible Borrower'
WHEN DischargeType = 'tlf' THEN 'Teacher Loan Forgiveness'
WHEN DischargeType = 'uns' THEN 'Unauthorized Signature/Payment'
WHEN DischargeType = 'unp' THEN 'Unpaid Refund'
END AS DischargeType
,UPPER(Servicer) AS Servicer
,'' AS Outstanding
--Intentionally using DateLoaded here instead of DateReceived
,SUM(CASE WHEN (DateLoaded > #StartDate AND DateLoaded < DATEADD(dd, 1, #EndDate)) THEN 1 ELSE 0 END) AS Claims_Loaded
,SUM(CASE WHEN DateCompleted IS NOT NULL AND Approve = 1 AND DateCompleted > #StartDate AND DateCompleted < DATEADD(dd, 1, #EndDate) THEN 1 ELSE 0 END) AS Claims_Approved
,SUM(CASE WHEN DateCompleted IS NOT NULL AND Approve = 0 AND DateCompleted > #StartDate AND DateCompleted < DATEADD(dd, 1, #EndDate) THEN 1 ELSE 0 END) AS Claims_Denied
,SUM(CASE WHEN DateCompleted IS NULL THEN 1 ELSE 0 END) AS Claims_Pending
,MIN(CASE WHEN DateCompleted IS NULL THEN MIN(DateReceived) ELSE '' END) AS Oldest_Claim
,ROUND((SUM(CASE WHEN DateCompleted IS NOT NULL AND Approve = 0 AND DateCompleted > #StartDate AND DateCompleted < DATEADD(dd, 1, #EndDate) THEN 1 ELSE 0 END) /
NULLIF(CAST(SUM(CASE WHEN (DateCompleted > #StartDate AND DateCompleted < DATEADD(dd, 1, #EndDate)) THEN 1 ELSE 0 END)AS Float),0) *100),2) AS Percent_Denied
FROM
Claims
WHERE
DischargeType IN ('atb','cls','death','dqs','fraud','id theft','ineligible borrower','tlf','uns','unp')
GROUP BY
DischargeType, Servicer
ORDER BY DischargeType, Servicer

You must change the expression:
MIN(CASE WHEN DateCompleted IS NULL THEN MIN(DateReceived) ELSE '' END)
To something like:
MIN(CASE WHEN DateCompleted IS NULL THEN (
select MIN(DateReceived) from ...
) ELSE '' END)
Probably you'll be better off including that subquery in a CTE.

Related

Query with Join of tables is taking long time to execute 5 min

SELECT
B.AccountBranchID
,B.VoucherNo
,B.BranchName AS BranchName
,B.InvoiceNo
,CONVERT(VARCHAR, B.InvoiceDate, 103) AS InvoiceDate
,CONVERT(VARCHAR, B.VoucherDate, 103) AS VoucherDate
,B.CustomerName
,B.RefID
,LN.AccountName AS LedgerName
,b.SalesPersonName AS SalesPersonName
,LN.LedgerCode
,B.AgentName
,B.ShipperName
,B.Segment
,B.TransactionType
,B.JobNo
,CONVERT(VARCHAR, B.JOBDate, 103) AS JOBDate
,B.MAWBNo
,B.HAWBNo
,B.AccountName
,B.LedgerCode AS AccountLedgerCode
,B.CurrencyCode
,ISNULL(B.Amount, 0) AS Amount
,B.ChargeExRate
,(CASE B.CRDR
WHEN 'CR' THEN (B.ChargeBaseAmount * -1)
ELSE B.ChargeBaseAmount
END) AS ChargeBaseAmount
,(CASE B.CRDR
WHEN 'CR' THEN 'Credit'
ELSE 'Debit'
END) AS CRDR
FROM VW_VoucherTR AS B
INNER JOIN VW_VoucherTR AS LN
ON B.VoucherID = LN.VoucherID
WHERE B.CompanyID = #CompanyID
AND (CASE #Type
WHEN 'I' THEN B.InvoiceDate
ELSE B.VoucherDate
END) BETWEEN ISNULL(#FromDate, (SELECT
FYearStart
FROM Secmst_FinancialYear
WHERE FyearId = #yearID)
) AND ISNULL(#ToDate, GETDATE())
AND (#Segment IS NULL
OR B.Segment = #Segment)
AND (#BranchMappingID IS NULL
OR B.BranchMappingID = #BranchMappingID)
AND B.VoucherTypeCode IN ('sv')
AND B.IsDeleted = 0
AND (B.GroupName <> 'Sundry Creditors'
AND B.GroupName <> 'Sundry Debtors')
AND LN.GroupName IN ('Sundry Debtors', 'Sundry Creditors')
The subquery in the BETWEEN is probably what is killing you. Have you looked at the execution plan?
BETWEEN ISNULL(#FromDate, (
SELECT FYearStart
FROM Secmst_FinancialYear
WHERE FyearId = #yearID
))
AND ISNULL(#ToDate, GETDATE())
What's happening is you are running that query across every row, and by my looks, that's unnecessary because you are only needing static dates there (not anything based on the joined rows.)
Try this:
DECLARE #FromDateActual datetime = ISNULL(#FromDate, (
SELECT FYearStart
FROM Secmst_FinancialYear
WHERE FyearId = #yearID
));
DECLARE #ToDateActual datetime = ISNULL(#ToDate, GETDATE());
SELECT B.AccountBranchID
,B.VoucherNo
,B.BranchName AS BranchName
,B.InvoiceNo
,convert(VARCHAR, B.InvoiceDate, 103) AS InvoiceDate
,convert(VARCHAR, B.VoucherDate, 103) AS VoucherDate
,B.CustomerName
,B.RefID
,LN.AccountName AS LedgerName
,b.SalesPersonName AS SalesPersonName
,LN.LedgerCode
,B.AgentName
,B.ShipperName
,B.Segment
,B.TransactionType
,B.JobNo
,convert(VARCHAR, B.JOBDate, 103) AS JOBDate
,B.MAWBNo
,B.HAWBNo
,B.AccountName
,B.LedgerCode AS AccountLedgerCode
,B.CurrencyCode
,ISNULL(B.Amount, 0) AS Amount
,B.ChargeExRate
,(
CASE B.CRDR
WHEN 'CR'
THEN (B.ChargeBaseAmount * - 1)
ELSE B.ChargeBaseAmount
END
) AS ChargeBaseAmount
,(
CASE B.CRDR
WHEN 'CR'
THEN 'Credit'
ELSE 'Debit'
END
) AS CRDR
FROM VW_VoucherTR AS B
INNER JOIN VW_VoucherTR AS LN ON B.VoucherID = LN.VoucherID
WHERE B.CompanyID = #CompanyID
AND (
CASE #Type
WHEN 'I'
THEN B.InvoiceDate
ELSE B.VoucherDate
END
) BETWEEN #FromDateActual
AND #ToDateActual
AND (
#Segment IS NULL
OR B.Segment = #Segment
)
AND (
#BranchMappingID IS NULL
OR B.BranchMappingID = #BranchMappingID
)
AND B.VoucherTypeCode IN ('sv')
AND B.IsDeleted = 0
AND (
B.GroupName <> 'Sundry Creditors'
AND B.GroupName <> 'Sundry Debtors'
)
AND LN.GroupName IN (
'Sundry Debtors'
,'Sundry Creditors'
)
Beyond that you could consider adding non-clustered indexes. The Query Analyzer may even suggest a couple. But you'll want to be careful there, depending on how the data is used and loaded, as too many indexes or large ones can lead to further performance issues in other places (row insertions, page fragmentation, etc).
There could be many reasons for it, but one thing is quite plain. The following part is not sargable.
(CASE #Type
WHEN 'I' THEN B.InvoiceDate
ELSE B.VoucherDate
END) BETWEEN ISNULL(#FromDate, (SELECT
FYearStart
FROM Secmst_FinancialYear
WHERE FyearId = #yearID)
) AND ISNULL(#ToDate, GETDATE())
Should be rewritten to be sargable, so that indexes can be used.
SELECT #FromDate = ISNULL(#FromDate, (SELECT
TOP 1 FYearStart
FROM Secmst_FinancialYear
WHERE FyearId = #yearID)) )
SELECT #ToDate = ISNULL(#ToDate, GETDATE())
SELECT
...
WHERE
...
AND
((#Type='I' AND B.InvoiceDate BETWEEN #FromDate AND #ToDate)
OR
(#Type<>'I' AND B.VoucherDate BETWEEN #FromDate AND #ToDate))
AND
...
Of course proper indexing is the way how to speed up your query, if no indexes are on InvoiceDate, VoucherDate, etc. then your query will use full table scan instead of index seek and it will be slow.

joining select statements?

I would like to do a inner join in my query but I don´t know how to summarize my two select statements into one query.
This is the first query:
select
Machine
, EventDefinition
, Duration
, sum(Duration) over (partition by 1) As Total
, Duration/sum(Duration) over (partition by 1)*100 AS Distribution
,case when EventCategory < 0.05 Then 'NOT INCL' ELSE 'OK' END AS Under3Min
from (
Select
SystemName AS Machine
, EventDefinition
, EventDate
, EventStartDateTime
, IsNull(EventEndDateTime, GETDATE()) as EventEndDateTime
, Sum(cast(EventEndDateTime - EventStartDateTime as float))*24 as Duration
,Sum(case when CustomEvent = 'without Stop' then cast(EventEndDateTime - EventStartDateTime as float)*24 else 0 end) as EventCategory
FROM tDataCategory
WHERE EventDate >= #StartDateTime
AND EventDate <= #EndDateTime
AND SystemName = '201'
Group BY SystemName, eventdefinition, eventstartdatetime, eventenddatetime, EventDefinition, EventDate, CustomEvent
) as t
WHERE CustomEvent <> 'without Stop'
OR (CustomEvent = 'without Stop' AND t.EventCategory >=0.05)
group by EventDefinition
, Duration
,Machine
,EventCategory
output:
and my second query:
SELECT DataValue = case when Prod = 0 then 0 else ISNULL(100.0 / Prod * Scrap, 0) end,
Value = GoodUnits/TheoreticalUnits *100,
FROM (
Select intervaldate as DateValue, intervalDateWeek as Datum, tsystem.Name as Name, ProductName as Product, teamname as Team,
SUM(case when IssueName in ('A1', 'A2') then calculationUnitsInitial else 0 end) as Scrap,
Sum(case when IssueName = 'Prod' then calculationUnitsInitial else 0 end) as Prod,
SUM(GoodUnits)
As GoodUnits,
SUM(TheoreticalUnits) As TheoreticalUnits,
from tCount inner join tsystem ON tCount.systemid = tsystem.id
where IntervalDate >= dateadd(wk, datediff(wk, 1, getdate()), 0)
and IntervalDate <= dateadd(wk, datediff(wk, 0, getdate()), 0)
AND ((DATEPART(dw, IntervalDate) + ##DATEFIRST) % 7) NOT IN (0,1)
and tsystem.Name = '201'
group by intervaldate, tsystem.Name, intervaldateweek, ProductName, teamname
) as s
output:
I tried it to add in my query two select statements. But if I do this the output is wrong. I really don´t know how I should join this two queries.
I would like to do then this calculation: Distribution * (1 - Value)
Distribution from the first query and Value from the second query
I assume the first and second result set has to be joined based on A.Machine=B.Name
Try like this,
SELECT A.Distribution * (1 - B.Value)
FROM (
SELECT Machine
,EventDefinition
,Duration
,sum(Duration) OVER (PARTITION BY 1) AS Total
,Duration / sum(Duration) OVER (PARTITION BY 1) * 100 AS Distribution
,CASE
WHEN EventCategory < 0.05
THEN 'NOT INCL'
ELSE 'OK'
END AS Under3Min
FROM (
SELECT SystemName AS Machine
,EventDefinition
,EventDate
,EventStartDateTime
,IsNull(EventEndDateTime, GETDATE()) AS EventEndDateTime
,Sum(cast(EventEndDateTime - EventStartDateTime AS FLOAT)) * 24 AS Duration
,Sum(CASE
WHEN CustomEvent = 'without Stop'
THEN cast(EventEndDateTime - EventStartDateTime AS FLOAT) * 24
ELSE 0
END) AS EventCategory
FROM tDataCategory
WHERE EventDate >= #StartDateTime
AND EventDate <= #EndDateTime
AND SystemName = '201'
GROUP BY SystemName
,eventdefinition
,eventstartdatetime
,eventenddatetime
,EventDefinition
,EventDate
,CustomEvent
) AS t
WHERE CustomEvent <> 'without Stop'
OR (
CustomEvent = 'without Stop'
AND t.EventCategory >= 0.05
)
GROUP BY EventDefinition
,Duration
,Machine
,EventCategory
) A
INNER JOIN (
SELECT DataValue = CASE
WHEN Prod = 0
THEN 0
ELSE ISNULL(100.0 / Prod * Scrap, 0)
END
,Value = GoodUnits / TheoreticalUnits * 100
,NAME
FROM (
SELECT intervaldate AS DateValue
,intervalDateWeek AS Datum
,tsystem.NAME AS NAME
,ProductName AS Product
,teamname AS Team
,SUM(CASE
WHEN IssueName IN (
'A1'
,'A2'
)
THEN calculationUnitsInitial
ELSE 0
END) AS Scrap
,Sum(CASE
WHEN IssueName = 'Prod'
THEN calculationUnitsInitial
ELSE 0
END) AS Prod
,SUM(GoodUnits) AS GoodUnits
,SUM(TheoreticalUnits) AS TheoreticalUnits
,
FROM tCount
INNER JOIN tsystem ON tCount.systemid = tsystem.id
WHERE IntervalDate >= dateadd(wk, datediff(wk, 1, getdate()), 0)
AND IntervalDate <= dateadd(wk, datediff(wk, 0, getdate()), 0)
AND ((DATEPART(dw, IntervalDate) + ##DATEFIRST) % 7) NOT IN (
0
,1
)
AND tsystem.NAME = '201'
GROUP BY intervaldate
,tsystem.NAME
,intervaldateweek
,ProductName
,teamname
) AS s
) B ON A.Machine = B.NAME

Zero being returned instead of empty string

I am working with a query:
USE SCRUMAPI2
DECLARE #userParam VARCHAR(100)
,#startDateParam DATETIME
,#endDateParam DATETIME
,#orgTeamPK VARCHAR(100)
,#teamId VARCHAR(100)
,#productId VARCHAR(100)
,#search VARCHAR(200)
SET #userParam = 'David Tunnell (tunnelld)'
SET #startDateParam = '2013-10-21 00:00:00'
SET #endDateParam = '2013-10-27 23:59:59'
SET #orgTeamPK = '%'
SET #teamId = '%'
SET #productId = '%'
SET #search = '%%'
SELECT RowType AS RowType
,Person AS Person
,Project AS Project
,ProjectType AS ProjectType
,StoryNumber AS StoryNumber
,StoryTitle AS StoryTitle
,Effort AS Effort
,Task AS Task
,OriginalEstimateHours AS OriginalEstimateHours
,MondayHours AS Monday
,TuesdayHours AS Tuesday
,WednesdayHours AS Wednesday
,ThursdayHours AS Thursday
,FridayHours AS Friday
,SaturdayHours AS Saturday
,SundayHours AS Sunday
,TotalHours AS Total
FROM (
-- DATE DISPLAY
SELECT '1' AS RowType
,'' AS Person
,'' AS Project
,'Category' AS ProjectType
,'Incident #' AS StoryNumber
,'' AS StoryTitle
,'' AS Effort
,'' AS Task
,'' AS OriginalEstimateHours
,'' AS Category
,'' AS IncidentNumber
,'' AS ApplicationName
,(CASE WHEN DATEDIFF(d, #startDateParam, #endDateParam) >= 7 THEN '' WHEN DATEDIFF(d, #startDateParam, #endDateParam) <= 5 THEN '' WHEN DATEPART(dw, DATEADD(DAY, 0, #startDateParam)) = 2 THEN CONVERT(VARCHAR(10), DATEADD(DAY, 0, #startDateParam), 111) ELSE '' END) AS MondayHours
,(CASE WHEN DATEDIFF(d, #startDateParam, #endDateParam) >= 7 THEN '' WHEN DATEDIFF(d, #startDateParam, #endDateParam) <= 5 THEN '' WHEN DATEPART(dw, DATEADD(DAY, 1, #startDateParam)) = 3 THEN CONVERT(VARCHAR(10), DATEADD(DAY, 1, #startDateParam), 111) ELSE '' END) AS TuesdayHours
,(CASE WHEN DATEDIFF(d, #startDateParam, #endDateParam) >= 7 THEN '' WHEN DATEDIFF(d, #startDateParam, #endDateParam) <= 5 THEN '' WHEN DATEPART(dw, DATEADD(DAY, 2, #startDateParam)) = 4 THEN CONVERT(VARCHAR(10), DATEADD(DAY, 2, #startDateParam), 111) ELSE '' END) AS WednesdayHours
,(CASE WHEN DATEDIFF(d, #startDateParam, #endDateParam) >= 7 THEN '' WHEN DATEDIFF(d, #startDateParam, #endDateParam) <= 5 THEN '' WHEN DATEPART(dw, DATEADD(DAY, 3, #startDateParam)) = 5 THEN CONVERT(VARCHAR(10), DATEADD(DAY, 3, #startDateParam), 111) ELSE '' END) AS ThursdayHours
,(CASE WHEN DATEDIFF(d, #startDateParam, #endDateParam) >= 7 THEN '' WHEN DATEDIFF(d, #startDateParam, #endDateParam) <= 5 THEN '' WHEN DATEPART(dw, DATEADD(DAY, 4, #startDateParam)) = 6 THEN CONVERT(VARCHAR(10), DATEADD(DAY, 4, #startDateParam), 111) ELSE '' END) AS FridayHours
,(CASE WHEN DATEDIFF(d, #startDateParam, #endDateParam) >= 7 THEN '' WHEN DATEDIFF(d, #startDateParam, #endDateParam) <= 5 THEN '' WHEN DATEPART(dw, DATEADD(DAY, 5, #startDateParam)) = 7 THEN CONVERT(VARCHAR(10), DATEADD(DAY, 5, #startDateParam), 111) ELSE '' END) AS SaturdayHours
,(CASE WHEN DATEDIFF(d, #startDateParam, #endDateParam) >= 7 THEN '' WHEN DATEDIFF(d, #startDateParam, #endDateParam) <= 5 THEN '' WHEN DATEPART(dw, DATEADD(DAY, 6, #startDateParam)) = 1 THEN CONVERT(VARCHAR(10), DATEADD(DAY, 6, #startDateParam), 111) ELSE '' END) AS SundayHours
,'' AS TotalHours
--
UNION ALL
--
-- GRAND TOTALS
--
SELECT '2' AS RowType
,'All Personnel' AS Person
,'' AS Project
,'' AS ProjectType
,'' AS StoryNumber
,'' AS StoryTitle
,'' AS Effort
,'Total:' AS Task
,'' AS OriginalEstimateHours
,'' AS Category
,'' AS IncidentNumber
,'' AS ApplicationName
,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 2 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS Monday
,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 3 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS Tuesday
,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 4 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS Wednesday
,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 5 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS Thursday
,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 6 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS Friday
,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 7 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS Saturday
,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 1 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS Sunday
,CAST(SUM(DTH.[Hours]) AS VARCHAR(20)) AS Total
FROM DailyTaskHours DTH
LEFT JOIN Task TSK ON DTH.TaskId = TSK.PK_Task
LEFT JOIN Story STY ON TSK.StoryId = STY.PK_Story
LEFT JOIN NonScrumStory NSS ON DTH.NonScrumStoryId = NSS.PK_NonScrumStory
LEFT JOIN Sprint SPT ON STY.SprintId = SPT.PK_Sprint
LEFT JOIN Product PDT ON STY.ProductId = PDT.PK_Product
LEFT JOIN ProductTeamUser PTU ON TSK.ProductTeamUserId = PTU.PK_ProductTeamUser
LEFT JOIN [User] USR ON PTU.UserId = USR.PK_User
LEFT JOIN OrganizationalTeam OLT ON USR.OrganizationalTeamId = OLT.PK_OrganizationalTeam
LEFT JOIN UserAuthorization UAN ON (
PDT.PK_Product = UAN.ProductId
AND USR.OrganizationalTeamId = UAN.OrganizationalTeamId
AND UAN.Deleted IS NULL
)
WHERE DTH.PointPerson LIKE #userParam
AND ActivityDate >= #startDateParam
AND ActivityDate <= #endDateParam
AND COALESCE(OLT.PK_OrganizationalTeam, '') LIKE #orgTeamPK
AND (
COALESCE(UAN.ProductId, '') LIKE #productId
OR COALESCE(UAN.OrganizationalTeamId, '') LIKE #teamId
)
AND (
(
STY.Number LIKE #search
OR STY.Number IS NULL
)
OR (
STY.Title LIKE #search
OR STY.Number IS NULL
)
OR (
TSK.NAME LIKE #search
OR STY.Number IS NULL
)
)
UNION ALL
--
-- Details by PERSON, PROJECT, SPRINT, STORY, TASK
--
SELECT '3' AS RowType
,DTH.PointPerson AS Person
,COALESCE(PDT.[Name], APP.AppName) AS Project
,(
CASE WHEN (
STY.KanBanProductId IS NOT NULL
AND STY.SprintId IS NULL
) THEN 'KanBan' WHEN (
STY.KanBanProductId IS NULL
AND STY.SprintId IS NOT NULL
) THEN 'Sprint' ELSE SCY.Catagory END
) AS ProjectType
,COALESCE(STY.[Number], NSS.IncidentNumber) AS StoryNumber
,COALESCE(STY.Title, NSS.[Description]) AS StoryTitle
,STY.Effort AS Effort
,COALESCE(TSK.[Name], '') AS Task
,TSK.OriginalEstimateHours AS OriginalEstimateHours
,SCY.Catagory AS Category
,NSS.IncidentNumber AS IncidentNumber
,APP.AppName AS ApplicationName
,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 2 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS MondayHours
,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 3 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS TuesdayHours
,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 4 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS WednesdayHours
,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 5 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS ThursdayHours
,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 6 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS FridayHours
,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 7 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS SaturdayHours
,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 1 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS SundayHours
,CAST(SUM(DTH.[Hours]) AS VARCHAR(20)) AS TotalHours
FROM DailyTaskHours DTH
LEFT JOIN Task TSK ON DTH.TaskId = TSK.PK_Task
LEFT JOIN Story STY ON TSK.StoryId = STY.PK_Story
LEFT JOIN NonScrumStory NSS ON DTH.NonScrumStoryId = NSS.PK_NonScrumStory
LEFT JOIN SupportCatagory SCY ON NSS.CatagoryId = SCY.PK_SupportCatagory
LEFT JOIN [Application] APP ON NSS.ApplicationId = APP.PK_Application
LEFT JOIN Sprint SPT ON STY.SprintId = SPT.PK_Sprint
LEFT JOIN Product PDT ON STY.ProductId = PDT.PK_Product
LEFT JOIN ProductTeamUser PTU ON TSK.ProductTeamUserId = PTU.PK_ProductTeamUser
LEFT JOIN [User] USR ON PTU.UserId = USR.PK_User
LEFT JOIN OrganizationalTeam OLT ON USR.OrganizationalTeamId = OLT.PK_OrganizationalTeam
LEFT JOIN UserAuthorization UAN ON (
PDT.PK_Product = UAN.ProductId
AND USR.OrganizationalTeamId = UAN.OrganizationalTeamId
AND UAN.Deleted IS NULL
)
WHERE DTH.PointPerson LIKE #userParam
AND ActivityDate >= #startDateParam
AND ActivityDate <= #endDateParam
AND COALESCE(OLT.PK_OrganizationalTeam, '') LIKE #orgTeamPK
AND (
COALESCE(UAN.ProductId, '') LIKE #productId
OR COALESCE(UAN.OrganizationalTeamId, '') LIKE #teamId
)
AND (
(
STY.Number LIKE #search
OR STY.Number IS NULL
)
OR (
STY.Title LIKE #search
OR STY.Number IS NULL
)
OR (
TSK.NAME LIKE #search
OR STY.Number IS NULL
)
)
GROUP BY DTH.PointPerson
,PDT.[Name]
,SPT.[Name]
,SPT.[Description]
,STY.[Number]
,STY.Title
,TSK.[Name]
,SCY.Catagory
,NSS.IncidentNumber
,APP.AppName
,STY.KanBanProductId
,STY.SprintId
,NSS.[Description]
,TSK.OriginalEstimateHours
,STY.Effort
HAVING SUM(DTH.[Hours]) > 0
--
UNION ALL
--
-- Sub-TOTAL by PERSON
--
SELECT '4' AS RowType
,DTH.PointPerson AS Person
,'' AS Project
,'' AS ProjectType
,'' AS StoryNumber
,'' AS StoryTitle
,'' AS Effort
,'Subtotal:' AS Task
,'' AS OriginalEstimateHours
,'' AS Category
,'' AS IncidentNumber
,'' AS ApplicationName
,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 2 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS MondayHours
,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 3 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS TuesdayHours
,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 4 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS WednesdayHours
,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 5 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS ThursdayHours
,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 6 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS FridayHours
,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 7 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS SaturdayHours
,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 1 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS SundayHours
,CAST(SUM(DTH.[Hours]) AS VARCHAR(20)) AS TotalHours
FROM DailyTaskHours DTH
LEFT JOIN Task TSK ON DTH.TaskId = TSK.PK_Task
LEFT JOIN Story STY ON TSK.StoryId = STY.PK_Story
LEFT JOIN NonScrumStory NSS ON DTH.NonScrumStoryId = NSS.PK_NonScrumStory
LEFT JOIN SupportCatagory SCY ON NSS.CatagoryId = SCY.PK_SupportCatagory
LEFT JOIN [Application] APP ON NSS.ApplicationId = APP.PK_Application
LEFT JOIN Sprint SPT ON STY.SprintId = SPT.PK_Sprint
LEFT JOIN Product PDT ON STY.ProductId = PDT.PK_Product
LEFT JOIN ProductTeamUser PTU ON TSK.ProductTeamUserId = PTU.PK_ProductTeamUser
LEFT JOIN [User] USR ON PTU.UserId = USR.PK_User
LEFT JOIN OrganizationalTeam OLT ON USR.OrganizationalTeamId = OLT.PK_OrganizationalTeam
LEFT JOIN UserAuthorization UAN ON (
PDT.PK_Product = UAN.ProductId
AND USR.OrganizationalTeamId = UAN.OrganizationalTeamId
AND UAN.Deleted IS NULL
)
WHERE DTH.PointPerson LIKE #userParam
AND ActivityDate >= #startDateParam
AND ActivityDate <= #endDateParam
AND COALESCE(OLT.PK_OrganizationalTeam, '') LIKE #orgTeamPK
AND (
COALESCE(UAN.ProductId, '') LIKE #productId
OR COALESCE(UAN.OrganizationalTeamId, '') LIKE #teamId
)
AND (
(
STY.Number LIKE #search
OR STY.Number IS NULL
)
OR (
STY.Title LIKE #search
OR STY.Number IS NULL
)
OR (
TSK.NAME LIKE #search
OR STY.Number IS NULL
)
)
GROUP BY DTH.PointPerson
HAVING SUM(DTH.[Hours]) > 0
) AS My_View
ORDER BY Person
,RowType
,Project
,ProjectType
,StoryNumber
,StoryTitle
,Task
And this is what is being returned:
I have Effort and OriginalEstimateHours set to be empty but 0 is returning. How can I make the cells blank?
I suspect that STY.Effort and TSK.OriginalEstimateHours (in the SELECT clause for rows of RowType 3) are numeric.
From the documentation for UNION:
The definitions of the columns that are part of a UNION operation do not have to be the same, but they must be compatible through implicit conversion. When data types differ, the resulting data type is determined based on the rules for data type precedence.
(My emphasis)
Wrap those columns in CONVERT(varchar(20),STY.Effort) so that the type chosen for those columns is varchar rather than a numeric type.
Their types are INT and BIGINT,
If you want an empty string, and not 0 or NULL, you will need to use the CAST or CONVERT functions to cast the column to a varchar type. You can't put an empty string in a number column. You may also need to then use a CASE statement to tranform a 0 string into an empty string.
When you assign empty string, depends on the datatype, it is converted to a different value. 0 for integer, 1900-01-01 for date, etc. Refer this for more information
http://beyondrelational.com/modules/2/blogs/70/posts/10841/empty-string-and-default-values.aspx

Join multiple queries with different search criteria

I have 4 queries that are identical with the exception of one of the criteria clauses at the end. I am trying to find a way to condense these 4 into 1, if possible. Currently, a program that we wrote calls these 4 statements through 4 stored procedures, but if I can make that 1 call that returns all 4, that would be great. Here's the bulk of the statement:
SELECT SUM(PausedTime) AS PausedMode
FROM UsageStats
WHERE StartDate >= CONVERT(VARCHAR(8), #StartDate, 112) AND StopDate < CONVERT(VARCHAR(8), #EndDate, 112)
AND LocationID = #LocationID
AND SystemID = #SystemID
AND PlayingArea = #PlayingArea
AND PausedTime > 0
I have 3 more of these and the only thing that changes is the field in the SUM calculation (all SUM fields are of type int):
SUM(PlayModeTime) AS PlayModeTime
SUM(RecordModeTime) AS RecordModeTime
SUM(ReplayModeTime) AS ReplayModeTime
and the last AND criteria
AND PlayModeTime > 0
AND RecordModeTime > 0
AND ReplayModeTime > 0
I tried using the CASE statement in the select clause but it failed:
SELECT
playMode = (CASE WHEN PlayModeTime > 0 THEN SUM(PlayModeTime) END),
pausedMode = (CASE WHEN PausedTime > 0 THEN SUM(PausedTime) END),
recordMode = (CASE WHEN RecordModeTime > 0 THEN SUM(RecordModeTime) END),
replayMode = (CASE WHEN ReplayModeTime > 0 THEN SUM(ReplayModeTime) END)
FROM UsageStats
WHERE StartDate >= CONVERT(VARCHAR(8), #StartDate, 112) AND StopDate < CONVERT(VARCHAR(8), #EndDate, 112)
AND LocationID = #LocationID
AND SystemID = #SystemID
AND PlayingArea = #PlayingArea
GROUP BY PlayModeTime, PausedTime, RecordModeTime, ReplayModeTime
I'd like to get something like this:
PlayModeTime | PausedMode | RecordModeTime | ReplayModeTime
---------------------------------------------------------------
200 340 10 55
Any help is appreciated.
I don't see why you need those conditions at all, since SUM will add zero when the value is 0. Can't you just SUM all of your columns?:
SELECT
playMode = SUM(PlayModeTime),
pausedMode = SUM(PausedTime),
recordMode = SUM(RecordModeTime),
replayMode = SUM(ReplayModeTime)
FROM UsageStats
WHERE StartDate >= CONVERT(VARCHAR(8), #StartDate, 112)
AND StopDate < CONVERT(VARCHAR(8), #EndDate, 112)
AND LocationID = #LocationID
AND SystemID = #SystemID
AND PlayingArea = #PlayingArea
You need to move the sum outside of the case statement:
SELECT
playMode = SUM(CASE WHEN PlayModeTime > 0 THEN PlayModeTime ELSE 0 END),
pausedMode = SUM(CASE WHEN PausedTime > 0 THEN PausedTime ELSE 0 END),
recordMode = SUM(CASE WHEN RecordModeTime > 0 THEN RecordModeTime ELSE 0 END),
replayMode = SUM(CASE WHEN ReplayModeTime > 0 THEN ReplayModeTime ELSE 0 END)
FROM UsageStats
WHERE StartDate >= CONVERT(VARCHAR(8), #StartDate, 112) AND StopDate < CONVERT(VARCHAR(8), #EndDate, 112)
AND LocationID = #LocationID
AND SystemID = #SystemID
AND PlayingArea = #PlayingArea
GROUP BY PlayModeTime, PausedTime, RecordModeTime, ReplayModeTime
The reason is that the case will be evaluated for each row. In your example, you're taking the sum of the column, but only for that row.
This only differs from Lamak's answer above in that it will treat negative values as zeroes in the sum.

Combining SQL Server Queries

I am using SQL Server and I have two tables and I would like to combine into one query that I can use to fill a gridview.
Table1 dbo.Work
UID (PK, int)
Tech_Ticket (int)
RMA_Ticket (int)
Region (nchar10)
Completed (nchar10)
FA (nchar10)
Agent (nvarchar50)
Tracking (nvarchar50)
Date_Added (date)
Date_Updated (date)
Table2 dbo.Orders
UID (PK, int)
Order (int)
Agent (nvarchar50)
Ticket (int)
Notes (nvarchar50)
Right now I have them setup as two separate queries and two separate tables.
Query1:
SELECT [Agent],
SUM(CASE WHEN [Date_Added] BETWEEN #startDate AND #endDate THEN 1 ELSE 0 END) AS 'New ',
SUM(CASE WHEN [Date_Updated] BETWEEN #startDate AND #endDate THEN 1 ELSE 0 END) AS 'Worked',
SUM(CASE WHEN [Completed] = 'yes' AND [Date_Updated] BETWEEN #startDate AND #endDate THEN 1 ELSE 0 END) AS 'Completed',
SUM(CASE WHEN [Failure_Analysis] = 'yes' AND [Date_Updated] BETWEEN #startDate AND #endDate THEN 1 ELSE 0 END) AS 'FA'
FROM Work
GROUP BY [Agent]
Query2:
SELECT [Agent]
SUM(CASE WHEN [Date] BETWEEN #startDate AND #endDate THEN 1 ELSE 0 END) AS 'Orders'
FROM Orders
GROUP BY [Agent]
Is there a way to combine these two queries into one?
You can JOIN them. Assuming that Work is the main table, it should be like this:
SELECT A.*, B.Orders
FROM ( SELECT [Agent],
SUM(CASE WHEN [Date_Added] BETWEEN #startDate AND #endDate THEN 1 ELSE 0 END) AS 'New',
SUM(CASE WHEN [Date_Updated] BETWEEN #startDate AND #endDate THEN 1 ELSE 0 END) AS 'Worked',
SUM(CASE WHEN [Completed] = 'yes' AND [Date_Updated] BETWEEN #startDate AND #endDate THEN 1 ELSE 0 END) AS 'Completed',
SUM(CASE WHEN [Failure_Analysis] = 'yes' AND [Date_Updated] BETWEEN #startDate AND #endDate THEN 1 ELSE 0 END) AS 'FA'
FROM Work
GROUP BY [Agent]) A
LEFT JOIN (SELECT [Agent]
SUM(CASE WHEN [Date] BETWEEN #startDate AND #endDate THEN 1 ELSE 0 END) AS 'Orders'
FROM Orders
GROUP BY [Agent]) B
ON A.[Agent] = B.[Agent]