Result set not returning what is expected - sql

I am working on a query and am getting results I don't expect. Here is the query:
USE SCRUMAPI2
DECLARE #userParam VARCHAR(100)
,#startDateParam DATETIME
,#endDateParam DATETIME
,#orgTeamPK VARCHAR(100)
,#teamId VARCHAR(100)
,#productId VARCHAR(100)
SET #userParam = '%'
SET #startDateParam = '2013-10-14 00:00:00'
SET #endDateParam = '2013-10-20 23:59:59'
SET #orgTeamPK = '%'
SET #teamId = '%'
SET #productId = '%'
SELECT '3' AS RowType
,DTH.PointPerson AS Person
,(
CASE
WHEN USR.[Deleted] IS NULL
THEN 'Active'
ELSE 'Inactive'
END
) AS [Status]
,USR.OrganizationalTeamId AS OrganizationalTeam
,COALESCE(PDT.[Name], APP.AppName) AS Project
,(
CASE
WHEN TSK.NAME IS NULL
THEN NULL
WHEN SPT.[Name] + ' - ' + SPT.[Description] IS NULL
THEN 'KanBan'
ELSE SPT.[Name] + ' - ' + SPT.[Description]
END
) AS Sprint
,COALESCE(STY.[Number], SCY.Catagory) AS Story
,COALESCE(TSK.[Name], NSS.IncidentNumber) AS Task
,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 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 SupportCatagory SCY ON NSS.CatagoryId = SCY.PK_SupportCatagory
LEFT JOIN [Application] APP ON NSS.ApplicationId = APP.PK_Application
LEFT JOIN UserAuthorization UAN1 ON (
PDT.PK_Product = UAN1.ProductId
AND UAN1.Deleted IS NULL
)
LEFT JOIN UserAuthorization UAN2 ON (
OLT.PK_OrganizationalTeam = UAN2.OrganizationalTeamId
AND UAN2.Deleted IS NULL
)
WHERE DTH.PointPerson LIKE #userParam
AND ActivityDate >= #startDateParam
AND ActivityDate <= #endDateParam
AND COALESCE(USR.OrganizationalTeamId, '') LIKE #orgTeamPK
AND (
COALESCE(UAN1.ProductId, '') LIKE #productId
OR COALESCE(UAN2.OrganizationalTeamId, '') LIKE #teamId
)
GROUP BY DTH.PointPerson
,PDT.[Name]
,SPT.[Name]
,SPT.[Description]
,STY.[Number]
,NSS.IncidentNumber
,TSK.[Name]
,OLT.[Name]
,USR.[Deleted]
,APP.AppName
,SCY.Catagory
,NSS.IncidentNumber
,USR.OrganizationalTeamId
HAVING SUM(DTH.[Hours]) > 0
Here is part of the result set:
For the results of the first user two of the OrganizationTeams column cells return NULL. I don't understand why this is, this user is assigned the org team of 3:
Why isn't it returning 3 for all cells of this user and how can I ensure it does?

Your OrganizationalTeam Column is joined in via DailyTaskHours > Task > ProductTeamUser > User. Each join can result in a NULL value so check each of these joins. Try running that Query with SELECT * and using a WHERE to return only one of those two rows.

Related

Exclude records with column value starting with '836'

So my latest issue is I need to be able to exclude records with claim numbers that start with '836'. This seems pretty straight forward, but nothing I've tried seems to be working, as I'm still getting back claim numbers starting with '836'. I've tried using NOT LIKE and NOT IN.
Could I please be advised what I'm doing wrong? I'm including the query and my comments. Thanks in advance for your input.
DECLARE #StartDate AS DateTime = '1/1/2017'
IF OBJECT_ID('tempdb..##ProducerCommBridge') IS NOT NULL
DROP TABLE ##ProducerCommBridge;
SELECT DISTINCT [ProducerCommBridgeKey]
,[PolicyAgreementNumber]
,[CommissionStartDate]
,[CommissionEndDate]
INTO ##ProducerCommBridge
FROM [dbo].[DimProducerCommBridge]
;
IF OBJECT_ID('tempdb..##FctLossData') IS NOT NULL
DROP TABLE ##FctLossData;
CREATE TABLE ##FctLossData (
[QIPS_LPRG_SID] numeric(10,0) null,
[PACClaimID] nvarchar(50) NULL,
[EquipmentID] int null,
[ClaimID] [int] NOT NULL,
[ClaimNumber] [varchar](34) NOT NULL,
[CreateDate] [datetime] NOT NULL,
[LossDate] [datetime] NOT NULL,
[ProCloseDate] [datetime] NULL,
[ProducerCommBridgeKey] [int] NOT NULL,
[ClaimStatus] [varchar](12) NULL,
[ContractNumber] [varchar](30) NULL,
[PolicyID] [varchar](20) NULL,
[CustomerID] [nvarchar](15) NULL,
[ProductID] [nvarchar](5) NULL,
[CatastropheID] [int] NULL,
[InsuranceClassCode] [varchar](1000) NULL,
[EquipmentName] [varchar](1000) NULL,
[EquipmentClassName] [varchar](1000) NULL,
[EquipmentDescription] [nvarchar](1000) NULL,
[RegionCode] [nvarchar](2) NULL,
[CountryCode] [nvarchar](3) NULL,
[ClaimLossType] [nvarchar](50) NULL,
[CauseOfLoss] [nvarchar](255) NULL,
[EnrollmentID] [nvarchar](50) NULL,
[CoverageID] [int] NULL,
[CoverageEffectiveDate] [datetime] NULL,
[CustomerAccountNumber] [nvarchar](50) NULL,
[PaidLossAmount] [money] NULL,
[CaseReserveAmount] [money] NULL,
[RecoveryReserveAmount] [money] NULL,
[SalvageRecoveryAmount] [money] NULL,
[SubroRecoveryAmount] [money] NULL,
[TotalRecoveryAmount] [money] NULL,
[AllocatedLAEAmount] [money] NULL
)
;
INSERT INTO ##FctLossData
--DECLARE #StartDate AS DateTime = '1/1/2017'
SELECT
qle.LPRG_SID
,lc.PACClaimID
,ems.EquipmentID
,c.ClaimID
,(c.ClaimPrefix + '-' + CONVERT(varchar, c.ClaimNumber)) AS ClaimNumber
,CONVERT(date, CreateDate) AS CreateDate
,CONVERT(date, c.LossDate) AS LossDate
,CASE WHEN DATEPART(hh, EffectiveDate) < 17 then CONVERT(date, EffectiveDate) ELSE CONVERT(date, dateadd(dd, 1, EffectiveDate)) END as ProCloseDate
,-1 AS ProducerCommBridgeKey
,cs.ClaimStatus
,UPPER(LEFT(c.ContractNumber, 10)) AS ContractNumber
,CASE WHEN c.ContractNumber IS NOT NULL THEN LEFT(c.PolicyNumber, 7) ELSE c.PolicyNumber END AS PolicyID
,sCustomerID AS CustomerID
,CASE WHEN pro.sProductID = '9095' THEN '1095' ELSE pro.sProductID END AS ProductID
,c.CatastropheID
,CASE WHEN LTRIM(RTRIM(dbo.fn_clean_string(InsuranceClassCode))) = '' THEN 'UNKNOWN' ELSE COALESCE(UPPER(LTRIM(RTRIM(dbo.fn_clean_string(InsuranceClassCode)))), 'UNKNOWN') END AS InsuranceClassCode
,CASE WHEN LTRIM(RTRIM(dbo.fn_clean_string(EquipmentName))) = '' THEN 'UNKNOWN' ELSE COALESCE(UPPER(LTRIM(RTRIM(dbo.fn_clean_string(EquipmentName)))), 'UNKNOWN') END AS EquipmentName
,CASE WHEN EquipmentClassName IS NULL THEN 'UNKNOWN' ELSE UPPER(LTRIM(RTRIM(dbo.fn_clean_string(EquipmentClassName)))) END AS EquipmentClassName
,CASE WHEN EquipmentDescription IS NULL THEN 'UNKNOWN' ELSE UPPER(LTRIM(RTRIM(dbo.fn_clean_string(EquipmentDescription)))) END AS EquipmentDescription
,RegionCode
,CountryCode
,CASE WHEN ClaimLossType IS NULL THEN 'Unknown' ELSE ClaimLossType END AS ClaimLossType
,CASE WHEN CauseOfLoss IS NULL THEN 'Unknown' ELSE CauseOfLoss END AS CauseOfLoss
,CASE WHEN qc.CLAM_LPRG_SID IS NOT NULL THEN CONVERT(nvarchar(50), qle.LEAS_SID) WHEN lc.EnrollmentID IS NOT NULL THEN CONVERT(nvarchar(50), lc.EnrollmentID) ELSE NULL END AS EnrollmentID
,NULL AS CoverageID
,NULL AS CoverageEffectiveDate
,CASE WHEN qc.CLAM_LPRG_SID IS NOT NULL THEN CONVERT(nvarchar(50), qle.LEAS_LEASE_CODE) WHEN lc.EnrollmentID IS NOT NULL THEN CONVERT(nvarchar(50), lefs.ContractNumber) ELSE NULL END AS CustomerAccountNumber
,SUM(CASE WHEN Reserve = 0 AND Recovery = 0 AND TranTypeID = 1 THEN Amount END) AS PaidLossAmount
,SUM(CASE WHEN Reserve = 1 AND Recovery = 0 AND TranTypeID = 1 THEN Amount END) AS CaseReserveAmount
,SUM(CASE WHEN Reserve = 1 AND Recovery = 1 AND TranTypeID IN (1, 7, 8) THEN Amount END) AS RecoveryReserveAmount
,SUM(CASE WHEN Reserve = 0 AND Recovery = 1 AND TranTypeID = 8 THEN Amount END) AS SalvageRecoveryAmount
,SUM(CASE WHEN Reserve = 0 AND Recovery = 1 AND TranTypeID = 7 THEN Amount END) AS SubroRecoveryAmount
,SUM(CASE WHEN Reserve = 0 AND Recovery = 1 AND TranTypeID IN (1, 7, 8) THEN Amount END) AS TotalRecoveryAmount
,SUM(CASE WHEN Reserve = 0 AND Recovery = 0 AND TranTypeID = 6 THEN Amount END) AS AllocatedLAEAmount
FROM dbo.ExtPACTransaction t
INNER JOIN dbo.ExtPACClaim c ON t.ClaimID = c.ClaimID
--AND c.ClaimNumber NOT LIKE '836%'
INNER JOIN dbo.ExtPRSDEPolicy pol ON (CASE WHEN [ContractNumber] IS NOT NULL THEN LEFT(c.PolicyNumber, 7) ELSE c.PolicyNumber END) = pol.sPolicyID
INNER JOIN dbo.ExtPRSDECustomer cus ON pol.iCustomerKey = cus.iCustomerKey
INNER JOIN dbo.ExtPRSDEProduct pro ON pol.iProductKey = pro.iProductKey
LEFT OUTER JOIN dbo.ExtPACClaimStatus cs ON c.ClaimID = cs.ClaimID
LEFT OUTER JOIN dbo.ExtJWProductSegment jw ON pro.sProductID = jw.sProductID
LEFT OUTER JOIN dbo.ExtEMSEquipment ems ON c.EMIEquipmentID = CONVERT(varchar, ems.EquipmentNumber)
LEFT OUTER JOIN dbo.ExtQIPSClaims qc ON qc.CLAM_PAC_CLAIMID = c.ClaimID
LEFT OUTER JOIN dbo.ExtQIPSLeaseEnrollment qle ON qle.LPRG_SID = qc.CLAM_LPRG_SID
LEFT OUTER JOIN dbo.ExtLP2Claim lc ON lc.PACClaimID = c.ClaimID
LEFT OUTER JOIN dbo.ExtLP2EnrollmentForSearch lefs ON lefs.EnrollmentID = lc.EnrollmentID
WHERE c.LossDate >= #StartDate
--AND c.ClaimNumber NOT LIKE '836%' -- To remove FIS claims
--AND c.ClaimNumber NOT IN (SELECT c2.ClaimNumber FROM ExtPACClaim c2 WHERE ClaimNumber LIKE '836%')
AND c.isVoided = 0
AND (pro.sProductID = '9095' OR jw.sProductID IS NOT NULL)
GROUP BY qle.LPRG_SID
,lc.PACClaimID
,ems.EquipmentID
,c.ClaimID
,(c.ClaimPrefix + '-' + CONVERT(varchar, c.ClaimNumber))
,CONVERT(date, CreateDate)
,CONVERT(date, c.LossDate)
,CASE WHEN DATEPART(hh, t.EffectiveDate) < 17 then CONVERT(date, t.EffectiveDate) ELSE CONVERT(date, dateadd(dd, 1, t.EffectiveDate)) END
,cs.ClaimStatus
, UPPER(LEFT(c.ContractNumber, 10))
,CASE WHEN c.ContractNumber IS NOT NULL THEN LEFT(c.PolicyNumber, 7) ELSE c.PolicyNumber END
,sCustomerID
,CASE WHEN pro.sProductID = '9095' THEN '1095' ELSE pro.sProductID END
,c.CatastropheID
,CASE WHEN LTRIM(RTRIM(dbo.fn_clean_string(InsuranceClassCode))) = '' THEN 'UNKNOWN' ELSE COALESCE(UPPER(LTRIM(RTRIM(dbo.fn_clean_string(InsuranceClassCode)))), 'UNKNOWN') END
,CASE WHEN LTRIM(RTRIM(dbo.fn_clean_string(EquipmentName))) = '' THEN 'UNKNOWN' ELSE COALESCE(UPPER(LTRIM(RTRIM(dbo.fn_clean_string(EquipmentName)))), 'UNKNOWN') END
,CASE WHEN EquipmentClassName IS NULL THEN 'UNKNOWN' ELSE UPPER(LTRIM(RTRIM(dbo.fn_clean_string(EquipmentClassName)))) END
,CASE WHEN EquipmentDescription IS NULL THEN 'UNKNOWN' ELSE UPPER(LTRIM(RTRIM(dbo.fn_clean_string(EquipmentDescription)))) END
,RegionCode
,CountryCode
,CASE WHEN ClaimLossType IS NULL THEN 'Unknown' ELSE ClaimLossType END
,CASE WHEN CauseOfLoss IS NULL THEN 'Unknown' ELSE CauseOfLoss END
,CASE WHEN qc.CLAM_LPRG_SID IS NOT NULL THEN CONVERT(nvarchar(50), qle.LEAS_SID) WHEN lc.EnrollmentID IS NOT NULL THEN CONVERT(nvarchar(50), lc.EnrollmentID) ELSE NULL END
,CASE WHEN qc.CLAM_LPRG_SID IS NOT NULL THEN CONVERT(nvarchar(50), qle.LEAS_LEASE_CODE) WHEN lc.EnrollmentID IS NOT NULL THEN CONVERT(nvarchar(50), lefs.ContractNumber) ELSE NULL END
--ORDER BY ClaimNumber DESC
;
--To view records
SELECT *
FROM ##FctLossData
WHERE ClaimNumber LIKE '836%'
I added a column ClaimNumberWithoutPrefix and filter based on this. Your original ClaimNumber has something like this at the beginning c.ClaimPrefix + '-'. Be aware that if c.ClaimPrefix is null then the whole expressions is null. To avoid this you can use concat(c.ClaimPrefix + '-', c.ClaimNumber)
SELECT
qle.LPRG_SID
,lc.PACClaimID
,ems.EquipmentID
,c.ClaimID
,(c.ClaimPrefix + '-' + CONVERT(varchar, c.ClaimNumber)) AS ClaimNumber
,ClaimNumber as ClaimNumberWithoutPrefix
,CONVERT(date, CreateDate) AS CreateDate
,CONVERT(date, c.LossDate) AS LossDate
,CASE WHEN DATEPART(hh, EffectiveDate) < 17 then CONVERT(date, EffectiveDate) ELSE CONVERT(date, dateadd(dd, 1, EffectiveDate)) END as ProCloseDate
,-1 AS ProducerCommBridgeKey
,cs.ClaimStatus
,UPPER(LEFT(c.ContractNumber, 10)) AS ContractNumber
,CASE WHEN c.ContractNumber IS NOT NULL THEN LEFT(c.PolicyNumber, 7) ELSE c.PolicyNumber END AS PolicyID
,sCustomerID AS CustomerID
,CASE WHEN pro.sProductID = '9095' THEN '1095' ELSE pro.sProductID END AS ProductID
,c.CatastropheID
,CASE WHEN LTRIM(RTRIM(dbo.fn_clean_string(InsuranceClassCode))) = '' THEN 'UNKNOWN' ELSE COALESCE(UPPER(LTRIM(RTRIM(dbo.fn_clean_string(InsuranceClassCode)))), 'UNKNOWN') END AS InsuranceClassCode
,CASE WHEN LTRIM(RTRIM(dbo.fn_clean_string(EquipmentName))) = '' THEN 'UNKNOWN' ELSE COALESCE(UPPER(LTRIM(RTRIM(dbo.fn_clean_string(EquipmentName)))), 'UNKNOWN') END AS EquipmentName
,CASE WHEN EquipmentClassName IS NULL THEN 'UNKNOWN' ELSE UPPER(LTRIM(RTRIM(dbo.fn_clean_string(EquipmentClassName)))) END AS EquipmentClassName
,CASE WHEN EquipmentDescription IS NULL THEN 'UNKNOWN' ELSE UPPER(LTRIM(RTRIM(dbo.fn_clean_string(EquipmentDescription)))) END AS EquipmentDescription
,RegionCode
,CountryCode
,CASE WHEN ClaimLossType IS NULL THEN 'Unknown' ELSE ClaimLossType END AS ClaimLossType
,CASE WHEN CauseOfLoss IS NULL THEN 'Unknown' ELSE CauseOfLoss END AS CauseOfLoss
,CASE WHEN qc.CLAM_LPRG_SID IS NOT NULL THEN CONVERT(nvarchar(50), qle.LEAS_SID) WHEN lc.EnrollmentID IS NOT NULL THEN CONVERT(nvarchar(50), lc.EnrollmentID) ELSE NULL END AS EnrollmentID
,NULL AS CoverageID
,NULL AS CoverageEffectiveDate
,CASE WHEN qc.CLAM_LPRG_SID IS NOT NULL THEN CONVERT(nvarchar(50), qle.LEAS_LEASE_CODE) WHEN lc.EnrollmentID IS NOT NULL THEN CONVERT(nvarchar(50), lefs.ContractNumber) ELSE NULL END AS CustomerAccountNumber
,SUM(CASE WHEN Reserve = 0 AND Recovery = 0 AND TranTypeID = 1 THEN Amount END) AS PaidLossAmount
,SUM(CASE WHEN Reserve = 1 AND Recovery = 0 AND TranTypeID = 1 THEN Amount END) AS CaseReserveAmount
,SUM(CASE WHEN Reserve = 1 AND Recovery = 1 AND TranTypeID IN (1, 7, 8) THEN Amount END) AS RecoveryReserveAmount
,SUM(CASE WHEN Reserve = 0 AND Recovery = 1 AND TranTypeID = 8 THEN Amount END) AS SalvageRecoveryAmount
,SUM(CASE WHEN Reserve = 0 AND Recovery = 1 AND TranTypeID = 7 THEN Amount END) AS SubroRecoveryAmount
,SUM(CASE WHEN Reserve = 0 AND Recovery = 1 AND TranTypeID IN (1, 7, 8) THEN Amount END) AS TotalRecoveryAmount
,SUM(CASE WHEN Reserve = 0 AND Recovery = 0 AND TranTypeID = 6 THEN Amount END) AS AllocatedLAEAmount
FROM dbo.ExtPACTransaction t
INNER JOIN dbo.ExtPACClaim c ON t.ClaimID = c.ClaimID
--AND c.ClaimNumber NOT LIKE '836%'
INNER JOIN dbo.ExtPRSDEPolicy pol ON (CASE WHEN [ContractNumber] IS NOT NULL THEN LEFT(c.PolicyNumber, 7) ELSE c.PolicyNumber END) = pol.sPolicyID
INNER JOIN dbo.ExtPRSDECustomer cus ON pol.iCustomerKey = cus.iCustomerKey
INNER JOIN dbo.ExtPRSDEProduct pro ON pol.iProductKey = pro.iProductKey
LEFT OUTER JOIN dbo.ExtPACClaimStatus cs ON c.ClaimID = cs.ClaimID
LEFT OUTER JOIN dbo.ExtJWProductSegment jw ON pro.sProductID = jw.sProductID
LEFT OUTER JOIN dbo.ExtEMSEquipment ems ON c.EMIEquipmentID = CONVERT(varchar, ems.EquipmentNumber)
LEFT OUTER JOIN dbo.ExtQIPSClaims qc ON qc.CLAM_PAC_CLAIMID = c.ClaimID
LEFT OUTER JOIN dbo.ExtQIPSLeaseEnrollment qle ON qle.LPRG_SID = qc.CLAM_LPRG_SID
LEFT OUTER JOIN dbo.ExtLP2Claim lc ON lc.PACClaimID = c.ClaimID
LEFT OUTER JOIN dbo.ExtLP2EnrollmentForSearch lefs ON lefs.EnrollmentID = lc.EnrollmentID
WHERE c.LossDate >= #StartDate
--AND c.ClaimNumber NOT LIKE '836%' -- To remove FIS claims
--AND c.ClaimNumber NOT IN (SELECT c2.ClaimNumber FROM ExtPACClaim c2 WHERE ClaimNumber LIKE '836%')
AND c.isVoided = 0
AND (pro.sProductID = '9095' OR jw.sProductID IS NOT NULL)
GROUP BY qle.LPRG_SID
,lc.PACClaimID
,ems.EquipmentID
,c.ClaimID
,(c.ClaimPrefix + '-' + CONVERT(varchar, c.ClaimNumber))
,ClaimNumber
,CONVERT(date, CreateDate)
,CONVERT(date, c.LossDate)
,CASE WHEN DATEPART(hh, t.EffectiveDate) < 17 then CONVERT(date, t.EffectiveDate) ELSE CONVERT(date, dateadd(dd, 1, t.EffectiveDate)) END
,cs.ClaimStatus
, UPPER(LEFT(c.ContractNumber, 10))
,CASE WHEN c.ContractNumber IS NOT NULL THEN LEFT(c.PolicyNumber, 7) ELSE c.PolicyNumber END
,sCustomerID
,CASE WHEN pro.sProductID = '9095' THEN '1095' ELSE pro.sProductID END
,c.CatastropheID
,CASE WHEN LTRIM(RTRIM(dbo.fn_clean_string(InsuranceClassCode))) = '' THEN 'UNKNOWN' ELSE COALESCE(UPPER(LTRIM(RTRIM(dbo.fn_clean_string(InsuranceClassCode)))), 'UNKNOWN') END
,CASE WHEN LTRIM(RTRIM(dbo.fn_clean_string(EquipmentName))) = '' THEN 'UNKNOWN' ELSE COALESCE(UPPER(LTRIM(RTRIM(dbo.fn_clean_string(EquipmentName)))), 'UNKNOWN') END
,CASE WHEN EquipmentClassName IS NULL THEN 'UNKNOWN' ELSE UPPER(LTRIM(RTRIM(dbo.fn_clean_string(EquipmentClassName)))) END
,CASE WHEN EquipmentDescription IS NULL THEN 'UNKNOWN' ELSE UPPER(LTRIM(RTRIM(dbo.fn_clean_string(EquipmentDescription)))) END
,RegionCode
,CountryCode
,CASE WHEN ClaimLossType IS NULL THEN 'Unknown' ELSE ClaimLossType END
,CASE WHEN CauseOfLoss IS NULL THEN 'Unknown' ELSE CauseOfLoss END
,CASE WHEN qc.CLAM_LPRG_SID IS NOT NULL THEN CONVERT(nvarchar(50), qle.LEAS_SID) WHEN lc.EnrollmentID IS NOT NULL THEN CONVERT(nvarchar(50), lc.EnrollmentID) ELSE NULL END
,CASE WHEN qc.CLAM_LPRG_SID IS NOT NULL THEN CONVERT(nvarchar(50), qle.LEAS_LEASE_CODE) WHEN lc.EnrollmentID IS NOT NULL THEN CONVERT(nvarchar(50), lefs.ContractNumber) ELSE NULL END
--ORDER BY ClaimNumber DESC
;
--To view records
SELECT *
FROM ##FctLossData
WHERE ClaimNumberWithoutPrefix LIKE '836%'
You can try [^] NotIn pattern matching in LIKE clause to filter out values, starting with 836. I have given sample code below for your reference. Read more about LIKE clause
CREATE TABLE #test(ClaimNumber VARCHAR(34))
INSERT INTO #test values('836789'),('567890'),('423897')
SELECT * FROM #test
WHERE claimNumber LIKE '[^8][^3][^6]%'
btw, I see that you are using CONVERT(VARCHAR, ClaimNumber). Always specify length for VARCHAR. If you do not specify length, it will be applying different default length in different places. In the case of CONVERT, it will be applying VARCHAR(30). In the table creation column definition, it will be applying VARCHAR(1). I would suggest you to read about this TSQL bad practice

Stored Procedure Insert Error: Column name or number of supplied values does not match table definition

This is the only error I get. Please Help. Thank you in advance.
After I successfully created and a stored procedure in SQL Server. I tried to execute it with the following (example only)
exec [dbo].ExportResourceTime 'ABC111', '', 3, 1, '2013-10-01', '2013-10-30', 1, 21
Then I get the following error. See attached photo.
This is the actual error in SSMS. Line 96 is the gray cursor on top of if #OrgUnit <> ''
This is the independent script which I think the error comes from. Correct me if I'm wrong.
Msg 213, Level 16, State 1, Procedure ExportResourceTime, Line 96
Insert Error: Column name or number of supplied values does not match table definition.
Code:
create procedure [dbo].ExportResourceTime
#ResourceID nvarchar(30),
#OrgUnit nvarchar(15),
#TimeDetail int,
#ExpenseDetail int,
#FromDate Datetime,
#ToDate Datetime,
#IncludeID int,
#TimeTypeGroup int
--1 = No Time Type Group
--2 = Group by Time Type
as
BEGIN
create table #ItemisedTimeandMaterials
(
IDNo int,
OrderBy1 varchar(60),
ItemDate datetime,--MOD005
RevenueTypeCode varchar(24),
TimeType varchar(24),
ProjectCode varchar(20),
taskUID int,
OutlineNum varchar(60),
taskname varchar(60),
activitycode varchar(24),
ActivityDesc varchar(60),
ResourceID nvarchar(24),
OrganizationID nvarchar(15),
EffectiveDate datetime,
firstname varchar(60),
lastname varchar(60),
ExpenseTypeCode varchar(24),
ExpenseTypeDesc varchar(60),
Hours decimal(8,2),
Rate decimal(8,2),
Total decimal(20,8),
Descr varchar(256), --MOD005 DM Added col for relevant detail for Expenses
TimeTypeCode nvarchar(10)
)
--GW: move this bit to the top--DONE
create table #Resources
(
ResourceID nvarchar(30),
OrganizationID nvarchar(15),
EffectiveDate datetime
)
if #ResourceID <> ''
begin
insert into #Resources (ResourceID,OrganizationID,EffectiveDate)
select ro.ResourceID, ro.OrganizationID, ro.EffectiveDate from ResourceOrganization ro,
(select ResourceID, MAX(EffectiveDate) as maxEffectivedate from dbo.ResourceOrganization
**where ResourceID = #ResourceID**
group by ResourceID) as maxresults
where ro.ResourceID = maxresults.ResourceID
and ro.EffectiveDate = maxresults.maxEffectivedate
end
if #OrgUnit <> ''
begin
insert into #Resources (ResourceID,OrganizationID,EffectiveDate)
Select ResourceID,OrganizationID,EffectiveDate from ResourceOrganization
where OrganizationID like '' + #OrgUnit + '%'
end
-- get actual time - REGULAR
insert into #ItemisedTimeandMaterials
select
Case when #IncludeID = 1 then b.timeID else '' end, --mod 07
e.lastname + e.firstname,
case when #TimeDetail = 2 then g.enddate else (case when #TimeDetail = 3 then b.TimeEntryDate else null end) end,--MOD005
'FEES',
'Regular',
b.projectcode,
b.taskuid,
f.outlinenum,
f.taskname,
b.ActivityCode,
c.ActivityDesc,
b.resourceID,
RES.OrganizationID,
e.firstname,
e.lastname,
'','', -- expense
sum(isnull(b.StandardHours,0)), -- MOD003 - added in isnull's
0,--h.StandardAmt,--b.NegotiatedChargeRate, --MOD005 Change to NegotiatedChargeRate from StandardChargeRate
0,--sum(isnull(b.StandardHours,0)* IsNull(h.standardAmt,0)),--sum(bd.BilledAmt),--MOD005 Change from BillableAmt feild (was incorrect for adjustments)
case when #TimeDetail = 3 then b.invoicecomment else '' end,--MOD005
case when #TimeTypeGroup = 2 then b.TimeTypeCode else '' end--MOD008
from time b
join activity c
on b.activitycode = c.activitycode
join resource e
on b.resourceID = e.resourceID
join project p
on b.ProjectCode=p.ProjectCode
and p.RevisionStatusCode='A'
join task f
on b.projectcode = f.projectcode
and b.taskuid =f.taskuid
and f.revisionnum = p.RevisionNum
join SCWeekEnding g
on b.TimeEntryDate between g.StartDate and g.EndDate
join #Resources RES
on b.ResourceID = RES.ResourceID
--left join ratesetresource h on h.resourceid = b.resourceid
where --b.projectcode = #PROJECTCODE and
b.statuscode in ('A','V','T')
and b.TimeEntryDate >= #FromDate
and b.TimeEntryDate <= #ToDate
and Isnull(b.StandardHours,0) <> 0
and b.resourceid in(Select ResourceId from #Resources)
group by
b.projectcode,
b.taskuid,
f.outlinenum,
f.taskname,
b.ActivityCode,
c.ActivityDesc,
b.resourceID,
RES.OrganizationID,
e.firstname,
e.lastname,
case when #TimeDetail = 2 then g.enddate else (case when #TimeDetail = 3 then b.TimeEntryDate else null end) end,--MOD005
case when #TimeDetail = 3 then b.invoicecomment else '' end,
Case when #IncludeID = 1 then b.timeID else '' end, --mod 07
case when #TimeTypeGroup = 2 then b.TimeTypeCode else '' end--MOD008
having sum(isnull(b.StandardHours,0)) <> 0
-- get actual time - OVERTIME
insert into #ItemisedTimeandMaterials
select
Case when #IncludeID = 1 then b.timeID else '' end, --mod 07
e.lastname + e.firstname,
case when #TimeDetail = 2 then g.enddate else (case when #TimeDetail = 3 then b.TimeEntryDate else null end) end,--MOD005
'FEES',
'Overtime',
--GW: need projectcode here--DONE
b.projectcode,
b.taskuid,
f.outlinenum,
f.taskname,
b.ActivityCode,
c.ActivityDesc,
b.resourceID,
RES.OrganizationID as OrgUnit,
e.firstname,
e.lastname,
'','', -- expense
sum(isnull(b.OvertimeHours,0)), -- MOD003 - added in isnull's
0,
0,
case when #TimeDetail = 3 then b.invoicecomment else '' end, --MOD005
case when #TimeTypeGroup = 2 then b.TimeTypeCode else '' end--MOD008
from time b
join activity c
on b.activitycode = c.activitycode
join resource e
on b.resourceID = e.resourceID
join project p
on b.ProjectCode=p.ProjectCode
and p.RevisionStatusCode='A'
join task f
on b.projectcode = f.projectcode
and b.taskuid =f.taskuid
and f.revisionnum = p.RevisionNum
join SCWeekEnding g
on b.TimeEntryDate between g.StartDate and g.EndDate
join #Resources RES
on b.ResourceID = RES.ResourceID
where
b.statuscode in ('A','V','T')
--and f.revisionnum = #latestapprovedrevision
and b.TimeEntryDate >= #FromDate
and b.TimeEntryDate <= #ToDate
and Isnull(b.OvertimeHours,0) <> 0
and b.resourceid in (select resourceid from #Resources)
group by
--GW: projectcode here--DONE
b.projectcode,
b.taskuid,
f.outlinenum,
f.taskname,
b.ActivityCode,
c.ActivityDesc,
b.resourceID,
RES.OrganizationID,
e.firstname,
e.lastname,
case when #TimeDetail = 2 then g.enddate else (case when #TimeDetail = 3 then b.TimeEntryDate else null end) end,--MOD005
case when #TimeDetail = 3 then b.invoicecomment else '' end,
case when #IncludeID = 1 then b.TimeID else '' end ,--mod 07
case when #TimeTypeGroup = 2 then b.TimeTypeCode else '' end--MOD008
having sum(isnull(b.Overtimehours,0)) <> 0
/**************** SECTION 7: OUTPUT DATA TO CRYSTAL REPORT ******************/
-- return data to the Crystal report only if taskuid are in table 1
select *
from #ItemisedTimeandMaterials
order by taskUID
drop table #Resources
drop table #ItemisedTimeandMaterials
END
GO
There are 23 columns in your #ItemisedTimeandMaterials temporary table while you are inserting only 22 values from select list.
When inserting into table with large number of columns with computed values from SELECT list, you can keep track of columns by giving alias name to each computed column same as the target temporary table column.
In this way you can easily compare the table columns and the columns in select list and find out missing column.
The missing column is EffectiveDate , add it to select list at correct position
Select
..
..
b.resourceID,
RES.OrganizationID,
RES.EffectiveDate, --- Missing column
e.firstname,
e.lastname,
...
..
check table and query (datatype and value Supplied Length) are Same and not
try this
if #ResourceID <> ''
begin
insert into #Resources (ResourceID,OrganizationID,EffectiveDate)
Select ro.ResourceID,
ro.OrganizationID,
ro.EffectiveDate
from ResourceOrganization ro
inner join (select ResourceID,
MAX(EffectiveDate) as maxEffectivedate
from dbo.ResourceOrganization
where ResourceID = #ResourceID
group by ResourceID) as maxresults on ro.ResourceID = maxresults.ResourceID
and ro.EffectiveDate = maxresults.maxEffectivedate
end
EDIT:
try executing it like this line
EXEC dbo.ExportResourceTime #ResourceID = N'ABC111', #OrgUnit = N'', #TimeDetail = 3, #ExpenseDetail = 1, #FromDate = '2013-10-01 00:00:00', #ToDate = '2013-10-30 00:00:00', #IncludeID = 1, #TimeTypeGroup = 21
I dont have your Database, so its hard to spot the fault from the other side of the world.
I have somewhat formatted your Script, But cant see anything wrong, I can't run the script aswell because of my above mentioned problem
CREATE PROCEDURE [dbo].ExportResourceTime
#ResourceID NVARCHAR(30),
#OrgUnit NVARCHAR(15),
#TimeDetail INT,
#ExpenseDetail INT,
#FromDate DATETIME,
#ToDate DATETIME,
#IncludeID INT,
#TimeTypeGroup INT
--1 = No Time Type Group
--2 = Group by Time Type
AS
BEGIN
CREATE TABLE #ItemisedTimeandMaterials
(
IDNo INT,
OrderBy1 VARCHAR(60),
ItemDate DATETIME,--MOD005
RevenueTypeCode VARCHAR(24),
TimeType VARCHAR(24),
ProjectCode VARCHAR(20),
taskUID INT,
OutlineNum VARCHAR(60),
taskname VARCHAR(60),
activitycode VARCHAR(24),
ActivityDesc VARCHAR(60),
ResourceID NVARCHAR(24),
OrganizationID NVARCHAR(15),
EffectiveDate DATETIME,
firstname VARCHAR(60),
lastname VARCHAR(60),
ExpenseTypeCode VARCHAR(24),
ExpenseTypeDesc VARCHAR(60),
Hours DECIMAL(8, 2),
Rate DECIMAL(8, 2),
Total DECIMAL(20, 8),
Descr VARCHAR(256), --MOD005 DM Added col for relevant detail for Expenses
TimeTypeCode NVARCHAR(10)
)
--GW: move this bit to the top--DONE
CREATE TABLE #Resources
(
ResourceID NVARCHAR(30),
OrganizationID NVARCHAR(15),
EffectiveDate DATETIME
)
IF #ResourceID <> ''
BEGIN
INSERT INTO #Resources
(ResourceID,
OrganizationID,
EffectiveDate)
SELECT ro.ResourceID,
ro.OrganizationID,
ro.EffectiveDate
FROM ResourceOrganization ro,
(SELECT ResourceID,
MAX(EffectiveDate) AS maxEffectivedate
FROM dbo.ResourceOrganization
WHERE ResourceID = #ResourceID
GROUP BY ResourceID) AS maxresults
WHERE ro.ResourceID = maxresults.ResourceID
AND ro.EffectiveDate = maxresults.maxEffectivedate
END
IF #OrgUnit <> ''
BEGIN
INSERT INTO #Resources
(ResourceID,
OrganizationID,
EffectiveDate)
SELECT ResourceID,
OrganizationID,
EffectiveDate
FROM ResourceOrganization
WHERE OrganizationID LIKE '' + #OrgUnit + '%'
END
-- get actual time - REGULAR
INSERT INTO #ItemisedTimeandMaterials
SELECT CASE WHEN #IncludeID = 1 THEN b.timeID
ELSE ''
END, --mod 07
e.lastname + e.firstname,
CASE WHEN #TimeDetail = 2 THEN g.enddate
ELSE (CASE WHEN #TimeDetail = 3 THEN b.TimeEntryDate
ELSE NULL
END)
END,--MOD005
'FEES',
'Regular',
b.projectcode,
b.taskuid,
f.outlinenum,
f.taskname,
b.ActivityCode,
c.ActivityDesc,
b.resourceID,
RES.OrganizationID,
e.firstname,
e.lastname,
'',
'', -- expense
SUM(ISNULL(b.StandardHours, 0)), -- MOD003 - added in isnull's
0,--h.StandardAmt,--b.NegotiatedChargeRate, --MOD005 Change to NegotiatedChargeRate from StandardChargeRate
0,--sum(isnull(b.StandardHours,0)* IsNull(h.standardAmt,0)),--sum(bd.BilledAmt),--MOD005 Change from BillableAmt feild (was incorrect for adjustments)
CASE WHEN #TimeDetail = 3 THEN b.invoicecomment
ELSE ''
END,--MOD005
CASE WHEN #TimeTypeGroup = 2 THEN b.TimeTypeCode
ELSE ''
END--MOD008
FROM time b
JOIN activity c ON b.activitycode = c.activitycode
JOIN resource e ON b.resourceID = e.resourceID
JOIN project p ON b.ProjectCode = p.ProjectCode
AND p.RevisionStatusCode = 'A'
JOIN task f ON b.projectcode = f.projectcode
AND b.taskuid = f.taskuid
AND f.revisionnum = p.RevisionNum
JOIN SCWeekEnding g ON b.TimeEntryDate BETWEEN g.StartDate AND g.EndDate
JOIN #Resources RES ON b.ResourceID = RES.ResourceID
--left join ratesetresource h on h.resourceid = b.resourceid
WHERE --b.projectcode = #PROJECTCODE and
b.statuscode IN ('A', 'V', 'T')
AND b.TimeEntryDate >= #FromDate
AND b.TimeEntryDate <= #ToDate
AND ISNULL(b.StandardHours, 0) <> 0
AND b.resourceid IN (SELECT ResourceId
FROM #Resources)
GROUP BY b.projectcode,
b.taskuid,
f.outlinenum,
f.taskname,
b.ActivityCode,
c.ActivityDesc,
b.resourceID,
RES.OrganizationID,
e.firstname,
e.lastname,
CASE WHEN #TimeDetail = 2 THEN g.enddate
ELSE (CASE WHEN #TimeDetail = 3 THEN b.TimeEntryDate
ELSE NULL
END)
END,--MOD005
CASE WHEN #TimeDetail = 3 THEN b.invoicecomment
ELSE ''
END,
CASE WHEN #IncludeID = 1 THEN b.timeID
ELSE ''
END, --mod 07
CASE WHEN #TimeTypeGroup = 2 THEN b.TimeTypeCode
ELSE ''
END--MOD008
HAVING SUM(ISNULL(b.StandardHours, 0)) <> 0
-- get actual time - OVERTIME
INSERT INTO #ItemisedTimeandMaterials
SELECT CASE WHEN #IncludeID = 1 THEN b.timeID
ELSE ''
END, --mod 07
e.lastname + e.firstname,
CASE WHEN #TimeDetail = 2 THEN g.enddate
ELSE (CASE WHEN #TimeDetail = 3 THEN b.TimeEntryDate
ELSE NULL
END)
END,--MOD005
'FEES',
'Overtime',
--GW: need projectcode here--DONE
b.projectcode,
b.taskuid,
f.outlinenum,
f.taskname,
b.ActivityCode,
c.ActivityDesc,
b.resourceID,
RES.OrganizationID AS OrgUnit,
e.firstname,
e.lastname,
'',
'', -- expense
SUM(ISNULL(b.OvertimeHours, 0)), -- MOD003 - added in isnull's
0,
0,
CASE WHEN #TimeDetail = 3 THEN b.invoicecomment
ELSE ''
END, --MOD005
CASE WHEN #TimeTypeGroup = 2 THEN b.TimeTypeCode
ELSE ''
END--MOD008
FROM time b
JOIN activity c ON b.activitycode = c.activitycode
JOIN resource e ON b.resourceID = e.resourceID
JOIN project p ON b.ProjectCode = p.ProjectCode
AND p.RevisionStatusCode = 'A'
JOIN task f ON b.projectcode = f.projectcode
AND b.taskuid = f.taskuid
AND f.revisionnum = p.RevisionNum
JOIN SCWeekEnding g ON b.TimeEntryDate BETWEEN g.StartDate AND g.EndDate
JOIN #Resources RES ON b.ResourceID = RES.ResourceID
WHERE b.statuscode IN ('A', 'V', 'T')
--and f.revisionnum = #latestapprovedrevision
AND b.TimeEntryDate >= #FromDate
AND b.TimeEntryDate <= #ToDate
AND ISNULL(b.OvertimeHours, 0) <> 0
AND b.resourceid IN (SELECT resourceid
FROM #Resources)
GROUP BY
--GW: projectcode here--DONE
b.projectcode,
b.taskuid,
f.outlinenum,
f.taskname,
b.ActivityCode,
c.ActivityDesc,
b.resourceID,
RES.OrganizationID,
e.firstname,
e.lastname,
CASE WHEN #TimeDetail = 2 THEN g.enddate
ELSE (CASE WHEN #TimeDetail = 3 THEN b.TimeEntryDate
ELSE NULL
END)
END,--MOD005
CASE WHEN #TimeDetail = 3 THEN b.invoicecomment
ELSE ''
END,
CASE WHEN #IncludeID = 1 THEN b.TimeID
ELSE ''
END,--mod 07
CASE WHEN #TimeTypeGroup = 2 THEN b.TimeTypeCode
ELSE ''
END--MOD008
HAVING SUM(ISNULL(b.Overtimehours, 0)) <> 0
/**************** SECTION 7: OUTPUT DATA TO CRYSTAL REPORT ******************/
-- return data to the Crystal report only if taskuid are in table 1
SELECT *
FROM #ItemisedTimeandMaterials
ORDER BY taskUID
DROP TABLE #Resources
DROP TABLE #ItemisedTimeandMaterials
END
GO

Getting rows returned that don't conform to a JOIN

I have two types of rows in a table:
There is the standard data, which is tied to a taskId and is loaded into the database during a process, the first two rows below are this type of data. The second type of data is not loaded in the process, it is inserted as part of a form. YOu can see the difference because the first type of data has a taskId and NonScrumStoryId is NULL. In the second case, NonScrumStoryId column is populated and TaskId is NULL.
I have a query to get data from this table:
DECLARE #startDateParam DATETIME
,#endDateParam DATETIME
,#productId VARCHAR(100)
,#search VARCHAR(100)
,#userParam VARCHAR(100)
,#orgTeamPK VARCHAR(100)
SET #startDateParam = '2013-11-25 00:00:00'
SET #endDateParam = '2013-12-01 23:59:59'
SET #productId = '%'
SET #search = '%%'
SET #userParam = '%'
SET #orgTeamPK = '%'
SELECT '3' AS RowType
,DTH.EnteredBy 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
,CONVERT(VARCHAR(20), STY.Effort) AS Effort
,COALESCE(TSK.[Name], '') AS Task
,CONVERT(VARCHAR(20), 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
,CAST(SUM(CASE WHEN DTH.Hours > 0 THEN DTH.[UserDifference] END) AS VARCHAR(20)) AS DifferentUsers
,CAST(SUM(CASE WHEN DTH.Hours > 0 THEN DTH.DoubleBookedFlag END) AS VARCHAR(20)) AS DoubleBookedFlag
,DTH.PointPerson AS PointPerson
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 [User] USR ON DTH.EnteredBy = USR.DisplayName
WHERE DTH.EnteredBy LIKE #userParam
AND ActivityDate >= #startDateParam
AND ActivityDate <= #endDateParam
AND PDT.PK_Product LIKE #productId
AND (
(
#orgTeamPK = '%'
AND (
USR.[OrganizationalTeamId] LIKE #orgTeamPK
OR USR.[OrganizationalTeamId] IS NULL
)
)
OR (
#orgTeamPK <> '%'
AND (USR.[OrganizationalTeamId] LIKE #orgTeamPK)
)
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.EnteredBy
,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
,DTH.PointPerson
HAVING SUM(DTH.[Hours]) > 0
My problem is that this query is only returning rows from the table that are from the process, it is not returning NonScrumStory columns and I need it to.
Edit: It appears part of the WHERE clause is causing the issue.
Ater investigation it probably has to do with this line:
AND PDT.PK_Product LIKE #productId
How can I remedy this?
You're joining Task using
LEFT JOIN Task TSK ON DTH.TaskId = TSK.PK_Task
then joining Story using
LEFT JOIN Story STY ON TSK.StoryId = STY.PK_Story
then joining Product using
LEFT JOIN Product PDT ON STY.ProductId = PDT.PK_Product
(Note the Task -> Story -> Product reliance)
Those joins are all fine, but you're filtering on Product using
AND PDT.PK_Product LIKE #productId
This will, no matter what, match rows that have a product like the parameter which in turn limits the results to rows that have stories, which limits to rows that have tasks.
You can check if #productId is null or equal to the product. This will allow you to return all rows if the parameter is not specified, or return rows filtered to the product.
...
AND ActivityDate <= #endDateParam
AND (#productId IS NULL OR PDT.PK_Product LIKE #productId)
AND (
...
If you need to always filter on product, then you'll probably have to use a UNION and select all rows with tasks in one, then all rows with NonScrumStory in the other.

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

SELECT SUMmed column during certain circumstances

As part of a complex query, I am trying sum the DifferentUsers field:
This is the actual table, the query I am using is:
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
,CONVERT(VARCHAR(20), STY.Effort) AS Effort
,COALESCE(TSK.[Name], '') AS Task
,CONVERT(VARCHAR(20), 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
,CAST(SUM(DTH.[UserDifference]) AS VARCHAR(20)) AS DifferentUsers
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 [User] USR ON DTH.PointPerson = USR.DisplayName
WHERE DTH.PointPerson LIKE #userParam
AND ActivityDate >= #startDateParam
AND ActivityDate <= #endDateParam
AND PDT.PK_Product LIKE #productId
AND (
(
#orgTeamPK = '%'
AND (
USR.[OrganizationalTeamId] LIKE #orgTeamPK
OR USR.[OrganizationalTeamId] IS NULL
)
)
OR (
#orgTeamPK <> '%'
AND (USR.[OrganizationalTeamId] LIKE #orgTeamPK)
)
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
The part of the query that I want to change is:
,CAST(SUM(DTH.[UserDifference]) AS VARCHAR(20)) AS DifferentUsers
As you can see, currently the query is performing as expected:
However, I only want the UserDifference to sum if Hours > 0.
I tried something like this:
,CAST(SUM(DTH.[UserDifference]) AS VARCHAR(20) WHERE DTH.Hours > 0) AS DifferentUsers
But the syntax is off and I am getting errors. How can I achieve the desired functionality?
You want a conditional SUM() and can use a CASE statement:
,CAST(SUM(CASE WHEN DTH.Hours > 0 THEN DTH.[UserDifference] END) AS VARCHAR(20)) AS DifferentUsers
Note: Some prefer to set an ELSE, but the default is NULL when a value is not captured by any of the CASE criteria, and since aggregates exclude NULL values you don't need it, the above and below will return identical results:
,CAST(SUM(CASE WHEN DTH.Hours > 0 THEN DTH.[UserDifference] ELSE 0 END) AS VARCHAR(20)) AS DifferentUsers