Error Converting data type varchar to numeric with reference to id - union

New to the forum, and new to sql for the most part.
I am getting an error message "Error Converting data type varchar to numeric." when i run the following script. It is referring to the supplier_id field.
I am looking to pull all supplier_id with purchases over the time period defined (1 and 2 years), the number of lines purchased, and the total spent.
select supplier_id,
sum(total_spend_last_12) as total_spend_last_12,
sum(total_spend_last_24) as total_spend_last_24,
count(number_lines_purchased_last_12) as number_lines_purchased_last_12,
count(number_lines_purchased_last_24) as number_lines_purchased_last_24
from (
select a.supplier_id,
sum(e.extended_cost) as total_spend_last_12,
count(e.item_id) as number_lines_purchased_last_12,
0 as total_spend_last_24,
0 as number_lines_purchased_last_24
from p21_view_po_hdr as a
inner join p21_view_po_line as b on b.po_no=a.po_no
inner join p21_view_supplier as c on c.supplier_id=a.supplier_id
left outer join p21_view_inventory_receipts_hdr as d on d.po_number=a.supplier_id
inner join p21_view_inventory_receipts_line as e on e.receipt_number=d.receipt_number
where e.date_created>= dateadd(day,-365,getdate()) and a.location_id='af'
group by a.supplier_id
union
select a.supplier_id,
0 as total_spend_last_12,
0 as number_lines_purchased_last_12,
sum(e.extended_cost) as total_spend_last_24,
count(e.item_id) as number_lines_purchased_last_24
from p21_view_po_hdr as a
inner join p21_view_po_line as b on b.po_no=a.po_no
inner join p21_view_supplier as c on c.supplier_id=a.supplier_id
left outer join p21_view_inventory_receipts_hdr as d on d.po_number=a.supplier_id
inner join p21_view_inventory_receipts_line as e on e.receipt_number=d.receipt_number
where e.date_created >= dateadd(day,-720,getdate()) and a.location_id='af'
group by a.supplier_id
)as tbl
group by tbl.supplier_id

Related

Group the count values

I want to get the count of property and building and building is linked with property. Below is the query I tried:
select
PT.PropertyTypeName,
Count(PropertyID) as ProperyCount,
Isnull((Select count(B.BuildingID)
from Building B
join Property P1
on B.PropertyID=P1.PropertyID
where B.PropertyID =P.PropertyID), 0) as BuildingsCount
from Property P
join PropertyType PT
on PT.PropertyTypeID = P.PropertyTypeID
left join AssetToFund AF
on AF.AssetID = P.AssetID
left join Fund F
on F.FundID = AF.FundID
left join Asset A
on A.AssetID = P.AssetID
left join Client C
on C.ClientID = F.ClientID
where C.ClientId=10000001
group by PT.PropertyTypeName,P.PropertyID
I expect values group of type
and I want to group the count with out duplicate of property-type name
sry for bad English.
Try to use the SUM() function on this subquery
Returns the sum of all the values, or only the DISTINCT values, in the expression. SUM can be used with numeric columns only. Null values are ignored.
MSDN
SUM(Select count(B.BuildingID)
from Building B
join Property P1
on B.PropertyID=P1.PropertyID
where B.PropertyID = P.PropertyID)
When you use GROUP BY then it groups data by columns which you've written in GROUP BY statement. You've written :
GROUP BY PT.PropertyTypeName,P.PropertyID`
it means that SQL Engine will get all unique combinations of PropertyTypeName, PropertyID. However, you want just unique PropertyTypeName. So write just this field into GROUP BY statement:
GROUP BY PT.PropertyTypeName
So complete query will look like this:
select
PT.PropertyTypeName,
Count(PropertyID) as ProperyCount,
Isnull((Select count(B.BuildingID)
from Building B
join Property P1
on B.PropertyID=P1.PropertyID
where B.PropertyID =P.PropertyID), 0) as BuildingsCount
from Property P
join PropertyType PT
on PT.PropertyTypeID = P.PropertyTypeID
left join AssetToFund AF
on AF.AssetID = P.AssetID
left join Fund F
on F.FundID = AF.FundID
left join Asset A
on A.AssetID = P.AssetID
left join Client C
on C.ClientID = F.ClientID
where C.ClientId=10000001
group by PT.PropertyTypeName

SSIS merge join lacks row (and also How to simulate SSIS join with tsql query)

In my project I have a merge join transformation, that uses inner join. It is supposed to join the files lookup with the rest of the data flow. However, the join seems to not include some rows, with files, even though it should? I'm trying to simulate the join in tsql, but I seem to be doing it wrong as it shows me the missing rows.
Here are the outputs I'm trying to join
Input A:
SELECT *
FROM
tblExpense expense
OUTER APPLY(
SELECT TOP 1 *
FROM tblExpenseDtl Details
WHERE expense.intExpenseID = Details.intExpenseID
ORDER BY Details.sintLineNo
) details
WHERE
expense.dtUpdateDateTime > '2017-06-01'
ORDER BY expense.intExpenseID desc
Input B:
SELECT f.*
FROM dbo.tblExpense e
JOIN tblExpenseDtl d ON d.intExpenseID = e.intExpenseID
JOIN tblExpReceiptFile f ON f.intExpenseDtlID = d.intExpenseDtlID
WHERE
e.dtUpdateDateTime > '2017-06-01'
ORDER BY e.intExpenseID desc
And the sql query that I thought would produce the same result as my SSIS inner join
SELECT *
FROM
tblExpense expense
OUTER APPLY(
SELECT TOP 1 *
FROM tblExpenseDtl Details
WHERE expense.intExpenseID = Details.intExpenseID
ORDER BY Details.sintLineNo
) details
inner join ( SELECT f.*
FROM dbo.tblExpense e
JOIN tblExpenseDtl d ON d.intExpenseID = e.intExpenseID
JOIN tblExpReceiptFile f ON f.intExpenseDtlID = d.intExpenseDtlID
WHERE
e.dtUpdateDateTime > '2017-06-01'
ORDER BY e.intExpenseID desc
) innerJ
WHERE
expense.dtUpdateDateTime > '2017-06-01'
ORDER BY expense.intExpenseID desc
The join key in the SSIS is the expense.intExpenseID = e.intExpenseID.
Input A gives 1 row, with an expenseID=X, and input B gives 2 rows with an expenseID=X
How are you sorting data before merging it? According to this SSIS is sorting in different way than SQL Server (in most cases). Maybe there is a problem.
Edit: What type is intExpenseID?

Select data from first date following a specific date (two tables joined)

I've searched but can't seem to get this exactly where I need it. This is in regards to Microsoft SQL Server.
I'm looking to join two tables, but only pull in data from the second table for the first date following the date in the first table. See code below.
I've got a table that shows emails sent to customers that looks like this:
SELECT
e.Name
,se.SubscriberID
,se.SendID
,c1.Id
,ds.Service_Num
,sub.EmailAddress
,se.EventDate as 'SentDate'
into #temp_billing_emails
FROM
bi_views.dbo.sfdcMC_SentEvent se
left join bi_views.dbo.sfdcmc_job j on j.jobid=se.sendid
left join bi_views.dbo.sfdcMC_Email e on e.id=j.emailid
left join bi_views.dbo.sfdcMC_Subscriber sub on sub.id=se.SubscriberID
left join sfdcprod.dbo.contact c1 on sub.subscriberkey=c1.id
left join bi_views.dbo.DIM_SERVICE_RF ds on c1.id=ds.ContractSignerContactID_bk
WHERE
e.name like '%Past Due%'
From there, I want to see how many days it took the email receiver to make their first payment following the received email. That's where I've got this:
SELECT
e.*
,z.zuora__createddate__c
,z.zuora__status__c
,z.zuora__amount__c
,datediff(dd,e.sentdate,z.Zuora__CreatedDate__c) DaysToPay
FROM
#temp_billing_emails e
left join sfdcprod.dbo.Service__C sc on e.Service_Num = right(sc.name,len(sc.name)-2)
left join sfdcprod.dbo.[zuora__customeraccount__c] a on sc.billing_account__c=a.id
left join sfdcprod.dbo.[zuora__payment__c] z on a.id=z.zuora__billingaccount__c
WHERE
datediff(dd,e.sentdate,z.Zuora__CreatedDate__c)>=0
and z.zuora__status__c not like 'Error'
That gets me all payments the customer has made after they received an email. What I need is just their first payment amount and the days it took following the email.
I tried the MIN() function like this:
SELECT TOP 100
e.EmailAddress
,e.SentDate
,e.Service_Num
,z.zuora__createddate__c
,z.zuora__status__c
,z.zuora__amount__c
,datediff(dd,e.sentdate,min(z.Zuora__CreatedDate__c)) DaysToPay
FROM
#temp_billing_emails e
left join sfdcprod.dbo.Service__C sc on e.Service_Num = right(sc.name,len(sc.name)-2)
left join sfdcprod.dbo.[zuora__customeraccount__c] a on sc.billing_account__c=a.id
left join sfdcprod.dbo.[zuora__payment__c] z on a.id=z.zuora__billingaccount__c
WHERE
datediff(dd,e.sentdate,z.Zuora__CreatedDate__c)>=0
and z.zuora__status__c not like 'Error'
GROUP BY
e.EmailAddress
,e.SentDate
,e.Service_Num
,z.zuora__createddate__c
,z.zuora__status__c
,z.zuora__amount__c
Any help would be GREATLY appreciated.
outer apply() is a good solution for this type of problem.
select e.*
, x.*
, DaysToPay = datediff(day,e.sentdate,x.Zuora__CreatedDate__c)
from #temp_billing_emails e
outer apply (
select top 1
z.zuora__createddate__c
, z.zuora__status__c
, z.zuora__amount__c
from sfdcprod.dbo.Service__C sc
inner join sfdcprod.dbo.[zuora__customeraccount__c] a
on sc.billing_account__c=a.id
and ds.Service_Num = right(sc.name,len(sc.name)-2)
inner join sfdcprod.dbo.[zuora__payment__c] z
on a.id=z.zuora__billingaccount__c
and z.zuora__status__c not like 'Error'
and z.Zuora__CreatedDate__c >= se.EventDate
order by z.Zuora__CreatedDate__c asc
) as x
I think this is how it would look without the temp table:
select
e.Name
, se.SubscriberID
, se.SendID
, c1.Id
, ds.Service_Num
, sub.EmailAddress
, se.EventDate as 'SentDate'
, x.zuora__createddate__c
, x.zuora__status__c
, x.zuora__amount__c
, DaysToPay = datediff(day,se.EventDate,x.Zuora__CreatedDate__c)
from bi_views.dbo.sfdcMC_SentEvent se
inner join bi_views.dbo.sfdcmc_job j on j.jobid=se.sendid
inner join bi_views.dbo.sfdcMC_Email e on e.id=j.emailid and e.name like '%Past Due%'
left join bi_views.dbo.sfdcMC_Subscriber sub on sub.id=se.SubscriberID
left join sfdcprod.dbo.contact c1 on sub.subscriberkey=c1.id
left join bi_views.dbo.DIM_SERVICE_RF ds on c1.id=ds.ContractSignerContactID_bk
outer apply (
select top 1
z.zuora__createddate__c
, z.zuora__status__c
, z.zuora__amount__c
from sfdcprod.dbo.Service__C sc
inner join sfdcprod.dbo.[zuora__customeraccount__c] a
on sc.billing_account__c=a.id
and ds.Service_Num = right(sc.name,len(sc.name)-2)
inner join sfdcprod.dbo.[zuora__payment__c] z
on a.id=z.zuora__billingaccount__c
and z.zuora__status__c not like 'Error'
and z.Zuora__CreatedDate__c >= se.EventDate
order by z.Zuora__CreatedDate__c asc
) as x

Original column name from T-SQL query that yields columns AFTER the original column name was reclassified

I have a relatively standard sql query with several table joins and where clauses that all relate a loan after it has been reclassified to ORE (Other Real Estate Owned). I am trying to list the value of one of the ORIGINAL fields (category) that has been changed now that it is ORE.
Say the original category was 1 for 'Consumer' but once the loan goes to ORE, the category is a 12 which includes ALL original categories (1,2,3,4)
Therein lies the problem - I need to show the ORE loans for only say categories 1 & 2. Nothing I've tried works - I'm assuming because the where clause at the bottom of the query specifies that I need various fields that all tie to the ORE status but NOT to the original categories. I've tried subqueries (don;t work because they are 'above' the main query's where clause...
Any general guidance would be greatly appreciated. Here's the query and the subquery below it:
SELECT
A.ACCTNO
E.SNAME,
B.OREO_ID,
A.OREODATE,
GC.CATEGORY
FROM
DBO.LOAN_SYSTEM AS A
LEFT OUTER JOIN DBO.ORE AS B
ON A.OREO_ID = B.OREO_ID
LEFT OUTER JOIN DBO.LOAN_TITLE AS C
ON A.OREO_ID = C.OREO_ID AND C.SEQ = 1
LEFT OUTER JOIN (SELECT * FROM DBO.LOAN_FC WHERE ISDELETED = 0 AND ISDISMISSED IS NULL) AS D
ON A.OREO_ID = D.OREO_ID
LEFT OUTER JOIN DBO.TBL_GROUP_CODES GC
ON E.[GROUP] = GC.GROUP_CODE
WHERE
D.FC_ID IS NOT NULL AND C.FORECLOSUREDATE IS NOT NULL AND GC.CATEGORY IN (1,2) --DOESN'T WORK BECAUSE ONCE IN OREO = 12
AND
E.STATUS NOT IN (2,8)
--SUBQUERY GETS ORIGINAL CATEGORY
SELECT
B.ACCTNO, C.CATEGORY
FROM DBO.LOAN_SYSTEM A
LEFT OUTER JOIN DBO.LOAN_DAILY_INFO B
ON B.ACCTNO = A.ACCTNO
AND B.TYPE = A.TYPE
LEFT OUTER JOIN DBO.TBL_GROUP_CODES C
ON C.GROUP_CODE = B.[GROUP]
LEFT OUTER JOIN DBO.TBL_LOAN_TYPES D
ON D.TYPE = A.TYPE
WHERE B.STATUS NOT IN (2,8)
AND C.CATEGORY IN (1,2)
I'm not 100% sure what you're trying to do here.. but you might need to use EXISTS here.
SELECT A.ACCTNO,
E.SNAME,
B.OREO_ID,
A.OREODATE,
GC.CATEGORY
FROM DBO.LOAN_SYSTEM AS A
LEFT OUTER JOIN DBO.ORE AS B ON A.OREO_ID = B.OREO_ID
LEFT OUTER JOIN DBO.LOAN_TITLE AS C ON A.OREO_ID = C.OREO_ID
AND C.SEQ = 1
LEFT OUTER JOIN (SELECT * FROM DBO.LOAN_FC WHERE ISDELETED = 0 AND ISDISMISSED IS NULL
) AS D ON A.OREO_ID = D.OREO_ID
LEFT OUTER JOIN DBO.TBL_GROUP_CODES GC ON D.[GROUP] = GC.GROUP_CODE
WHERE D.FC_ID IS NOT NULL
AND C.FORECLOSUREDATE IS NOT NULL
AND EXISTS (
SELECT 1
FROM DBO.LOAN_DAILY_INFO F
JOIN DBO.TBL_GROUP_CODES G ON G.GROUP_CODE = F.[GROUP]
WHERE F.STATUS NOT IN (2,8)
AND G.CATEGORY IN (1,2)
AND F.ACCTNO = A.ACCTNO
AND F.TYPE = A.TYPE
)
AND D.STATUS NOT IN (2,8)

Use groupby with inner join to get unique record on single column

I need unique record on colum a.[id] so I am using group but it getting error
Msg 8120, Level 16, State 1, Line 3
Column 'dbo.assessment_dfn.name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Query
SELECT a.[id] AS AssessmentID
--,ad.[code] AS Assessment_Dfn_Code
,ad.[name] AS Assessment_Dfn_name
,mdfn.[id] AS Module_Dfn_ID
,a.[student_stage]
,a.[assessments_sitting]
,a.[sitting_date]
,ads.[sitting_number]
,s.[id] AS StudentID
,a.[assessor] AS AssessorID
,mdfn.[lead] AS ModuleLead
,a.[submission_date]
,a.[status]
,a.[complete]
,a.[assessment]
,a.[saved]
,ele_cliPro.[grade] AS GradeID
,codGrd.[name] AS GradeName
FROM [adb_TestDb].[dbo].[assessments] AS a (NOLOCK)
INNER JOIN [adb_TestDb].[dbo].[student_stage] AS ss ON a.[student_stage] = ss.[id]
INNER JOIN [dbo].[assessment_dfn_sittings] ads WITH (NOLOCK) ON ads.[id] = a.[assessments_sitting]
INNER JOIN [adb_TestDb].[dbo].[students] AS s ON ss.student = s.[id]
INNER JOIN [dbo].[assessment_dfn] ad WITH (NOLOCK) ON ad.[id] = ads.[assessment]
INNER JOIN [dbo].[module_dfn] AS mdfn ON ad.[module] = mdfn.[id]
INNER JOIN [adb_TestDb].[dbo].[elements_clinicalprocedures] AS ele_cliPro ON a.[id] = ele_cliPro.[assessment]
INNER JOIN [adb_TestDb].[dbo].[codes_grade_details] AS codGrd ON ele_cliPro.[grade] = codGrd.[id] AND codGrd.[id] = 4
where a.id= 2532
group by a.[id]
As suggested by SQL you cannot get columns when using GROUP BY if they are not in that clause or in an aggregate function.
If you need only one record and you know all values are the same you could try to use an aggregate function for all the values required (eg MAX) but this solution should be used only if you are completely aware of getting only one among the possible values!

Resources