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
Related
i have a query in which i segregate old and new Employee i want to count how many New and old employees are there. how can i segregate and i dont want to use group by cluase.
here is my Query
((SELECT mock.EID,
mock.ECode,
mock.BaseCode,
mock.STATUS,
mock.EmpName,
mock.Desig,
mock.CMP_ID,
CASE WHEN podt.empid IS NULL THEN CAST(0 AS bit)ELSE CAST(1 AS bit)END AS [select],
CONVERT(varchar, mock.JoiningDate, 106) AS JoiningDate,
CASE
WHEN DATEDIFF(DAY, mock.JoiningDate, '1/31/' + CAST(DATEPART(YEAR, GETDATE()) AS varchar)) > 60 THEN 'Old'
ELSE 'New'
END AS StatusEmployee
FROM (SELECT E.EID,
E.ECode,
E.BaseCode,
CASE WHEN E.EActive = 0 THEN 'ACTIVE' ELSE 'IN ACTIVE' END AS STATUS,
E.EmpName,
D.DesigDesc AS Desig,
E.CMP_ID,
CAST(E.JoiningDate AS datetime) AS JoiningDate
FROM PostingDetail pd,
Employee_Profile E,
DESIGNATION D
WHERE pd.EmpId = E.EID
AND E.Desig = D.DesigCode
AND pd.SubLoc IN (6700, 20400, 21300, 21900)
AND pd.EndDate IS NULL
AND CMP_ID IN ('SZSPL')
AND CAST(E.JoiningDate AS datetime) BETWEEN CAST(E.JoiningDate AS datetime) AND '1/31/' + CAST(DATEPART(YEAR, GETDATE()) AS varchar)) mock
LEFT OUTER JOIN PostingDetail_training podt ON mock.EID = podt.empid));
select SUM (CASE WHEN tbl.StatusEmployee= 'New' then 1 else 0 end ) NewEmployee,SUM (CASE WHEN tbl.StatusEmployee= 'Old' then 1 else 0 end ) OldEmployee
from (
(select mock.EID, mock.ECode, mock.BaseCode, mock.STATUS, mock.EmpName, mock.Desig, mock.CMP_ID, case when podt.empid is null then cast(0 as bit) else cast(1 as bit) End [select] ,convert(varchar,mock.JoiningDate,106)JoiningDate,
case when DATEDIFF(day,mock.JoiningDate,'1/31/'+cast(DATEPART(year,getdate())as varchar)) > 60 then 'Old'
else 'New' end as StatusEmployee
from (
SELECT E.EID, E.ECode, E.BaseCode, CASE WHEN E.EActive = 0 THEN 'ACTIVE' ELSE 'IN ACTIVE' END AS STATUS, E.EmpName, D.DesigDesc As Desig, E.CMP_ID ,CAST(E.JoiningDate AS datetime) JoiningDate
FROM PostingDetail pd, Employee_Profile E, DESIGNATION D
Where pd.EmpId = E.EID AND E.Desig = D.DesigCode AND pd.SubLoc in(6700, 20400, 21300, 21900) AND pd.EndDate is null AND CMP_ID IN('SZSPL') and cast(E.JoiningDate as datetime) between cast(E.JoiningDate as datetime) and '1/31/'+cast(DATEPART(year,getdate())as varchar)) mock left outer join PostingDetail_training podt on mock.EID=podt.empid
)) tbl
Please I need to multiply total no of jobtype and the value of MEAL_Ticket for a particular date
SELECT DISTINCT
DATENAME(dw, Time) + ', ' + CONVERT(VARCHAR(12), Time, 107) AS Date_to_Display,Vale,
(SELECT COUNT(*) FROM CanLog AS c
WHERE c.Time= clog.Time AND jobtype = 'fulltime') AS Fulltime,
(SELECT COUNT(Jobtype) * SUM(Value) FROM CanLog
WHERE Time BETWEEN '2018-02-12' AND '2018-02-14' AND jobtype = 'fulltime' ) AS FulltimeTicket_Value,
(SELECT COUNT(*) FROM CanLog AS c
WHERE c.Time = clog.Time AND jobtype = 'contract') AS Contract,
(SELECT COUNT(*) FROM CanLog AS c
WHERE c.Time = clog.Time AND jobtype = 'casual') AS Casual
FROM
CanLog AS clog
WHERE
Time BETWEEN '2018-02-12' AND '2018-02-14'
GROUP BY
Time, Jobtype
ORDER BY
2 ASC
I got this error
Column 'CanLog.Value' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause
What I want is this output:
Fulltime FulltimeTicket_Value Contract Casual
2018/06/04 1 500(1*500) 6 2
2018/06/05 3 1500(3*500) 0 0
2018/06/06 0 0 (0*500) 3 1
2018/06/07 2 1000(2*500) 1 0
2018/06/08 1 500(1*500) 1 3
2018/06/09 0 0(0*500) 1 4
Please help
EDIT:
Sample table
CREATE TABLE [dbo].[CanLog]
(
[id] [int] IDENTITY(1,1) NOT NULL,
[Firstname] [nvarchar](50) NOT NULL,
[Designation] [nvarchar](50) NOT NULL,
[Jobtype] [nvarchar](50) NOT NULL,
[Employ_No] [nvarchar](50) NOT NULL,
[Receipt_No] [int] NOT NULL,
[Username] [nvarchar](50) NOT NULL,
[Time] [datetime] NOT NULL,
[Value] [int] NULL
) ON [PRIMARY]
Initial query has a lot of warning signs:
GROUP BY does not match SELECT
DISTINCT + GROUP BY
unnecessary subqueries could be replaced with conditional aggregation
positional ORDER BY
I would recommend to avoid column names such as Value/Time
Datename(dw, Time) + ', ' + CONVERT(VARCHAR(12), Time, 107) I would replace it with CAST(Time AS DATE)
Time BETWEEN '2018-02-12' AND '2018-02-14' this kind of comparison may be dangerous (as mentioned by #Gordon)
I believe you want something like:
SELECT
Date_to_Display = CAST(Time AS DATE),
Fulltime = SUM(CASE WHEN jobtype = 'fulltime' THEN 1 ELSE 0 END),
FulltimeTicket_Value = SUM(CASE WHEN jobtype = 'fulltime' THEN 1 ELSE 0 END) *
MAX(CASE WHEN jobtype = 'fulltime' THEN Value ELSE 0 END),
Contract = SUM(CASE WHEN jobtype = 'contract' THEN 1 ELSE 0 END),
Casual = SUM(CASE WHEN jobtype = 'casual' THEN 1 ELSE 0 END)
FROM
CanLog AS clog
WHERE
Time >= '2018-02-12' and time < '2018-02-15'
GROUP BY
CAST(Time AS DATE)
ORDER BY
CAST(Time AS DATE);
In addition to many of the points that Lukasz makes, you should avoid using between on date/time columns. A very good explanation is in Aaron Bertrand's blog What do Between and the Devil Have In Common.
You can also simplify the logic using indicator variables:
select cast(time as date) as Date_to_Display,
sum(is_fulltime) as Fulltime,
sum(value * is_fulltime) as FulltimeTicket_Value,
sum(is_contract) as Contract,
sum(is_casual) as Casual
from CanLog cl cross apply
(values (case when cl.jobtype = 'fulltime' then 1 else 0 end),
(case when cl.jobtype = 'contract' then 1 else 0 end),
(case when cl.jobtype = 'casual' then 1 else 0 end)
) v(is_contract, iscasual)
where Time >= '2018-02-12' and time < '2018-02-15'
group by cast(time as date)
order by cast(time as date);
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.
I have a table like this
I am trying to achieve a table like this:
this was my query.
select name,token , sum(qty) [Qty],sum(amount)from #temp
group by token,name
tried like this..
SELECT *
FROM (SELECT name,
qty,amt,
Token
FROM #temp1
) AS D
PIVOT(Sum(amt)
FOR Token IN ([10],[20],[100],[40],[5])) AS P
it is not working though.
Any help will be appreciated.
I think you can achieve it by the following statement:
SELECT
[Name],
SUM((CASE WHEN [Token] = 10 THEN [QTY] ELSE 0 END)) AS Token_10_QTY,
SUM((CASE WHEN [Token] = 10 THEN [amt] ELSE 0 END)) AS Token_10_amt,
SUM((CASE WHEN [Token] = 50 THEN [QTY] ELSE 0 END)) AS Token_50_QTY,
SUM((CASE WHEN [Token] = 50 THEN [amt] ELSE 0 END)) AS Token_50_amt,
SUM((CASE WHEN [Token] = 100 THEN [QTY] ELSE 0 END)) AS Token_100_QTY,
SUM((CASE WHEN [Token] = 100 THEN [amt] ELSE 0 END)) AS Token_100_amt
FROM
#temp1
GROUP BY
[Name]
assuming your columns QTY and amt are NOT NULL.
I hope it will help you some way.
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]