How to achieve this model - vb.net

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.

Related

SQL code to project how many clients will reach age 55 each month for a year

I am trying to get the number of clients who are currently >= age 55, which I've managed, but next I want to find out how many people will be >= 55 in a month's time, then in 2 month's time etc up to 12 months.
Here is what I have so far, but I'm not sure how to go about the next bit. Any help greatly appreciated! Thanks.
SELECT
SUM(CASE
WHEN [C].[BirthDate] > dateadd(year, -54, getdate()) AND [E].[MfChk4] = '0'
THEN 0
ELSE 1
END) AS [Age Eligible]
FROM
[dbo].[CR_Entity] [E]
LEFT OUTER JOIN [dbo].[CR_RefMaster] [RM]
ON [RM].[EntCode] = [E].[EntClient]
AND [RM].[Status] = '0'
LEFT OUTER JOIN [dbo].[Compliance] [C]
ON [C].[AddrCode] = [RM].[RefCode]
The result I want for the next bit will be something like...
You would have to write multiple case statements like:
SUM
(CASE WHEN [C].[BirthDate] > dateadd(month,-54*12+1, getdate())
AND [E].[MfChk4] = '0'
THEN 0 ELSE 1 END) AS Month1,
SUM
(CASE WHEN [C].[BirthDate] > dateadd(month,-54*12+2, getdate())
AND [E].[MfChk4] = '0'
THEN 0 ELSE 1 END) AS Month2,
.
.
.
SUM
(CASE WHEN [C].[BirthDate] > dateadd(month,-54*12+12, getdate())
AND [E].[MfChk4] = '0'
THEN 0 ELSE 1 END) AS Month12
To create the Naming convention you are looking, for you would have to use Dynamic SQL. You might have to change the query a bit, but the basics of it is:
--Declaring and calculating the Column Names
declare #test1 nvarchar(max),
#test2 nvarchar(max),
#test12 nvarchar(max)
set #test1='['+CAST(FORMAT(DATEADD(month,1,GETDATE()),'MMM-yy') as Varchar(20))+']'
set #test2='['+CAST(FORMAT(DATEADD(month,2,GETDATE()),'MMM-yy') as Varchar(20))+']'
.
.
.
set #test12='['+CAST(FORMAT(DATEADD(month,12,GETDATE()),'MMM-yy') as Varchar(20))+']'
--Writing the Dynamic Sql text
DECLARE #sql nvarchar(max)
SELECT #sql = N'SELECT SUM (CASE WHEN [C].[BirthDate] > dateadd(year, -54, getdate())
AND [E].[MfChk4] = ''0''
THEN 0 ELSE 1 END) AS [Age Eligible],
SUM
(CASE WHEN [C].[BirthDate] > dateadd(month,-54*12+1, getdate())
AND [E].[MfChk4] = ''0''
THEN 0 ELSE 1 END) AS' + #test1 + ',
SUM
(CASE WHEN [C].[BirthDate] > dateadd(month,-54*12+2, getdate())
AND [E].[MfChk4] = ''0''
THEN 0 ELSE 1 END) AS' + #test2 + ',
.
.
.
SUM
(CASE WHEN [C].[BirthDate] > dateadd(month,-54*12+12, getdate())
AND [E].[MfChk4] = ''0''
THEN 0 ELSE 1 END) AS' + #test12 + '
FROM [dbo].[CR_Entity] [E]
LEFT OUTER JOIN [dbo].[CR_RefMaster] [RM] ON [RM].[EntCode] = [E].[EntClient] AND [RM].[Status] = ''0''
LEFT OUTER JOIN [dbo].[Compliance] [C] ON [C].[AddrCode] = [RM].[RefCode]'
--Executing the Dynamic Sql query
EXEC sp_executesql #sql
You might want to start with one case statement to understand how it works and then implement it for the entire data.

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

Multiply two (2) columns of a table

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);

SQL Server 2005 : conversion failed when converting the varchar value '0.00' to data type int

When adding this line into my query:
convert(varchar(20), convert(varchar(20),
sum(case when tsr.other like '%aa%' then tsr.block1 else 0 end) +
sum(case when tsr.other like '%aa%' then tsr.block2 else 0 end) +
sum(case when tsr.other like '%aa%' then tsr.block3 else 0 end) +
sum(case when tsr.other like '%aa%' then tsr.block4 else 0 end)) * 450)
I get this error message:
Conversion failed when converting the varchar value '0.00' to data
type int
Data in block column is days - e.g. 10.0
Any ideas?
i've got it fixed, it was just changing the 450 to 450.0.
The reason for the varchars is that this is just 1 line from 1 of multiple unioned select statements.
10.0 isn't an int - it's a decimal.
Try
declare #i int
select #i = convert(decimal(9,4),'10.0')
select #i
and the conversion from the decimal to the int will be done implicitly.
'10.0' isn't an int/decimal - it's a varchar .
do any mathematical calculation only on decimal/numeric/float/int values.
SELECT convert(varchar(20), convert(decimal(10,2), sum(case when
tsr.other like '%aa%' then convert(decimal(10,2),tsr.block1) else 0
end) + sum(case when tsr.other like '%aa%' then
convert(decimal(10,2),tsr.block2) else 0 end) + sum(case when
tsr.other like '%aa%' then convert(decimal(10,2),tsr.block3) else 0
end) + sum(case when tsr.other like '%aa%' then
convert(decimal(10,2),tsr.block4) else 0 end)) * 450)

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]