IF, then, else in SQL query to combine multiple columns - sql

I currently have an SQL query that is used to create a matter report for our firms. The problem with it at the moment is that it creates six columns for client/party details which could be reduced to three columns to minimise confusion for the secretaries that will review before the report is used in marketing.
There's three client types - individual, joint party or organisation.
The six columns in the report are ClientFirstName, ClientLastName, ClientEmail (which are all populated if the ClientType is Individual) and PartyFirstName, PartyLastName, PartyEmail (which are all populated if the ClientType is Joint Part or Organisation - sometimes multiple results for each party member).
Here's the query:
SELECT DISTINCT
-- setup columns
[cases].[reference] as MatterNumber,
[dd_entity_d2].[type] as ClientType,
[dd_client].[clientname] as MatterName,
etClient.FirstName as ClientFirstName,
etClient.LastName as ClientLastName,
[dd_entity_d2].[email] as ClientEmail,
[dd_entity_d4].[firstname] as PartyFirstName,
[dd_entity_d4].[lastname] as PartyLastName,
[dd_entity_d4].[email] as PartyEmail,
etActing.[PreferredName] ActingPerson,
[cases].[category] as MatterType,
mt.CreatedOn as MatterOpened,
case mt.[Status]
when 0 then 'In Progress'
When 1 then 'On Hold'
when 2 then 'Completed'
when 3 then 'Not Proceeding'
else 'Unknown' end as MatterStatus
-- mt.LastUpdatedOn as LastModified,
-- end columns
-- setup data
FROM PracticeEvolve_doc.dbo.[cases]
INNER JOIN PracticeEvolve_c1.dbo.DocumaticsMap dm on dm.DocumaticsID = [cases].ID and dm.Entitytype = 'Matter'
INNER JOIN PracticeEvolve_c1.dbo.[Matter] mt on mt.Matterid = dm.ClickOneID
INNER JOIN PracticeEvolve_c1.dbo.[Client] cl on mt.ClientID = cl.ClientID
INNER JOIN PracticeEvolve_c1.dbo.[Entity] etClient on cl.EntityID = etClient.EntityID
LEFT JOIN PracticeEvolve_c1.dbo.EmployeeMatter emActing on emActing.MatterID = mt.MatterID and emActing.AssociationTypeID = 15
LEFT JOIN PracticeEvolve_c1.dbo.Employee eActing on eActing.EmployeeID = emActing.EmployeeID
LEFT JOIN PracticeEvolve_c1.dbo.Entity etActing on etActing.EntityID = eActing.EntityID
LEFT JOIN PracticeEvolve_doc.dbo.[dd_client] ON [dd_client].[id]=[cases].[clientid]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_manytomany] AS [dd_manytomanydd_entity_d2] ON [dd_manytomanydd_entity_d2].[fkid] = [dd_client].[fk_entities]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_entity] as [dd_entity_d2] ON [dd_entity_d2].[id] = [dd_manytomanydd_entity_d2].[pkid]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_manytomany] AS [dd_manytomanydd_party_d3] ON [dd_manytomanydd_party_d3].[fkid] = [dd_entity_d2].[fk_parties]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_party] as [dd_party_d3] ON [dd_party_d3].[id] = [dd_manytomanydd_party_d3].[pkid]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_manytomany] AS [dd_manytomanydd_entity_d4] ON [dd_manytomanydd_entity_d4].[fkid] = [dd_party_d3].[fk_entity]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_entity] as [dd_entity_d4] ON [dd_entity_d4].[id] = [dd_manytomanydd_entity_d4].[pkid]
-- end data
-- setup filters
WHERE [cases].[deleted]=0
AND DATEPART(m, mt.CreatedOn) = DATEPART(m, DATEADD(m, -1, getdate()))
AND DATEPART(yyyy, mt.CreatedOn) = DATEPART(yyyy, DATEADD(m, -1, getdate()))
-- AND mt.CreatedOn >= '2017-05-16'
-- AND [dd_entity_d2].[type] = 'Individual'
-- AND mt.LastUpdatedOn >= '2017-04-02'
-- AND mt.[status] = 0
-- end filters and query
What I'd like to do is have it just use the columns FirstName, LastName and Email so that it is populated with the individual's details if the ClientType is individual, or populated with the joint party's/organisation's details if the ClientType is something other than Individual.
Is this possible?
(as a bit of a disclaimer - I'm a novice with database queries, so may not know how to implement a specific statement or string)

You can use Case Statement. I assumed Client type is stored as text but you can change 'individual' to appropriate value.
SELECT DISTINCT
-- setup columns
[cases].[reference] as MatterNumber,
[dd_entity_d2].[type] as ClientType,
[dd_client].[clientname] as MatterName,
CASE WHEN [dd_entity_d2].[type] ='Individual' THEN etClient.FirstName ELSE [dd_entity_d4].[firstname] END AS FirstName,
CASE WHEN [dd_entity_d2].[type] ='Individual' THEN etClient.LastName ELSE [dd_entity_d4].[lastname] END AS LastName,
CASE WHEN [dd_entity_d2].[type] ='Individual' THEN [dd_entity_d2].[email] ELSE [dd_entity_d4].[email] END AS Email,
etActing.[PreferredName] ActingPerson,
[cases].[category] as MatterType,
mt.CreatedOn as MatterOpened,
case mt.[Status]
when 0 then 'In Progress'
When 1 then 'On Hold'
when 2 then 'Completed'
when 3 then 'Not Proceeding'
else 'Unknown' end as MatterStatus
-- mt.LastUpdatedOn as LastModified,
-- end columns
-- setup data
FROM PracticeEvolve_doc.dbo.[cases]
INNER JOIN PracticeEvolve_c1.dbo.DocumaticsMap dm on dm.DocumaticsID = [cases].ID and dm.Entitytype = 'Matter'
INNER JOIN PracticeEvolve_c1.dbo.[Matter] mt on mt.Matterid = dm.ClickOneID
INNER JOIN PracticeEvolve_c1.dbo.[Client] cl on mt.ClientID = cl.ClientID
INNER JOIN PracticeEvolve_c1.dbo.[Entity] etClient on cl.EntityID = etClient.EntityID
LEFT JOIN PracticeEvolve_c1.dbo.EmployeeMatter emActing on emActing.MatterID = mt.MatterID and emActing.AssociationTypeID = 15
LEFT JOIN PracticeEvolve_c1.dbo.Employee eActing on eActing.EmployeeID = emActing.EmployeeID
LEFT JOIN PracticeEvolve_c1.dbo.Entity etActing on etActing.EntityID = eActing.EntityID
LEFT JOIN PracticeEvolve_doc.dbo.[dd_client] ON [dd_client].[id]=[cases].[clientid]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_manytomany] AS [dd_manytomanydd_entity_d2] ON [dd_manytomanydd_entity_d2].[fkid] = [dd_client].[fk_entities]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_entity] as [dd_entity_d2] ON [dd_entity_d2].[id] = [dd_manytomanydd_entity_d2].[pkid]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_manytomany] AS [dd_manytomanydd_party_d3] ON [dd_manytomanydd_party_d3].[fkid] = [dd_entity_d2].[fk_parties]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_party] as [dd_party_d3] ON [dd_party_d3].[id] = [dd_manytomanydd_party_d3].[pkid]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_manytomany] AS [dd_manytomanydd_entity_d4] ON [dd_manytomanydd_entity_d4].[fkid] = [dd_party_d3].[fk_entity]
LEFT JOIN PracticeEvolve_doc.dbo.[dd_entity] as [dd_entity_d4] ON [dd_entity_d4].[id] = [dd_manytomanydd_entity_d4].[pkid]
-- end data
-- setup filters
WHERE [cases].[deleted]=0
AND DATEPART(m, mt.CreatedOn) = DATEPART(m, DATEADD(m, -1, getdate()))
AND DATEPART(yyyy, mt.CreatedOn) = DATEPART(yyyy, DATEADD(m, -1, getdate()))
-- AND mt.CreatedOn >= '2017-05-16'
-- AND [dd_entity_d2].[type] = 'Individual'
-- AND mt.LastUpdatedOn >= '2017-04-02'
-- AND mt.[status] = 0
-- end filters and query

Related

Can I make multiple records display values within the same record

I am using the following query to display records of customers and their disabilites. The query works, but the results show multiple records for the same case and customer where they have multiple disabilities. Is there a way to include all disabilites under one record, so it does not duplicate the entire record for a minor change in the data?
The following is my query in it's current state:
USE MyPersonalSupport_reporting
SELECT
SC.Name AS 'Sub-Contract',
CSCH.Received AS LiveDate,
CS.ServiceEndDate AS ServiceEndDate,
CS.CaseReference,
CONTACT.FirstName AS 'Forename',
CONTACT.LastName AS 'Surname',
CONTACT.DateOfBirth AS DOB,
CONTACT.DateOfDeath,
CONTACT.Age,
CCAV.ConcatenatedAddress AS 'Full Address',
LK1.Value AS Ethnicity,
LK2.Value AS Sex,
LK3.Value AS Religion,
LK4.Value AS Sexuality,
LK5.Value AS Transgender,
LK6.Value AS Nationality,
LK7.Value AS 'First Language',
SO.Name AS ServiceOffering,
LK.Value AS CaseStatus,
DATEDIFF(day, CSCH.Received, CS.serviceenddate) AS 'Days Occupied',
CONCAT (EMP.FirstName, ' ' , EMP.LastName) AS KeyWorker,
CASE WHEN CONTACT.HasDisibility = 1 THEN 'YES' ELSE 'NO' END AS HasDisability,
CASE WHEN DV.value = 'Autistic Spectrum Condition' THEN 'YES' ELSE 'NO' END AS AutisticSpectrumCondition,
CASE WHEN DV.value = 'Hearing Impairment' THEN 'YES' ELSE 'NO' END AS 'Hearing Impairment',
CASE WHEN DV.value = 'Learning Disability' THEN 'YES' ELSE 'NO' END AS 'Learning Disability',
CASE WHEN DV.value = 'Mental Health' THEN 'YES' ELSE 'NO' END AS 'Mental Health',
CASE WHEN DV.value = 'Mobility Disability' THEN 'YES' ELSE 'NO' END AS 'Mobility Disability',
CASE WHEN DV.value = 'Progressive Disability / Chronic Illness' THEN 'YES' ELSE 'NO' END AS 'Progressive Disability / Chronic Illness',
CASE WHEN DV.value = 'Visual Impairment' THEN 'YES' ELSE 'NO' END AS 'Visual Impairment',
CASE WHEN DV.value = 'Other' THEN 'YES' ELSE 'NO' END AS 'Other Disability',
CASE WHEN DV.value = 'Does not wish to disclose' THEN 'YES' ELSE 'NO' END AS 'Does not wish to disclose'
FROM [MyPersonalSupport_reporting].[Mps].[Cases] AS CS
INNER JOIN mps.CaseContracts AS CC ON CS.caseid = CC.caseid
INNER JOIN mps.CaseStatusChangeHistories AS CSCH ON CS.CaseId = CSCH.CaseId
INNER JOIN mps.Contacts AS CONTACT ON CS.CustomerId = CONTACT.ContactId
FULL OUTER JOIN mps.ContactCurrentAddress AS CCAV ON CONTACT.ContactID = CCAV.ContactId
FULL OUTER JOIN mps.LookupItems AS LK ON CSCH.StatusId = LK.LookupItemId
FULL OUTER JOIN mps.LookupItems AS LK1 ON CONTACT.EthnicityId = LK1.LookupItemId
FULL OUTER JOIN mps.LookupItems AS LK2 ON CONTACT.SexId = LK2.LookupItemId
FULL OUTER JOIN mps.LookupItems AS LK3 ON CONTACT.ReligionId = LK3.LookupItemId
FULL OUTER JOIN mps.LookupItems AS LK4 ON CONTACT.SexualityId = LK4.LookupItemId
FULL OUTER JOIN mps.LookupItems AS LK5 ON CONTACT.TransgenderId = LK5.LookupItemId
FULL OUTER JOIN mps.LookupItems AS LK6 ON CONTACT.NationalityId = LK6.LookupItemId
FULL OUTER JOIN mps.LookupItems AS LK7 ON CONTACT.FirstLanguageId = LK7.LookupItemId
FULL OUTER JOIN mps.SubContracts AS SC ON CC.SubContractId = SC.SubContractId
FULL OUTER JOIN mps.ServiceOfferings AS SO ON SC.ServiceOfferingId = SO.ServiceOfferingId
FULL OUTER JOIN mps.Employees AS EMP ON EMP.EmployeeId = CS.KeyWorkerId
FULL OUTER JOIN dbo.disabilitiescrosstab AS DV ON CONTACT.ContactId = DV.EntityID
WHERE
CSCH.Received >= '2000-01-01' AND CS.ServiceEndDate <= GETDATE()
AND CSCH.StatusId = 1392
AND CSCH.Archived = 0
AND CONTACT.Archived = 0
ORDER BY CS.CaseId
Although I don't know your use case exactly but I believe there is no need to do full outer join, you can get away with left join / inner join.
Step 1: You can use STRING_AGG for the "DisibilityName" column. Aggregate all disease for each entity ID
SELECT EntityID, STRING_AGG(DV_VALUE,",")
FROM
dbo.disabilitiescrosstab
GROUP BY EntityID
Step 2: then join aggregated table with your base table
Code(have removed few joins but the idea is same):
SELECT
SC.Name AS 'Sub-Contract',
CSCH.Received AS LiveDate,
CS.ServiceEndDate AS ServiceEndDate,
CS.CaseReference,
CONTACT.FirstName AS 'Forename',
CONTACT.LastName AS 'Surname',
CONTACT.DateOfBirth AS DOB,
CONTACT.DateOfDeath,
CONTACT.Age,
CCAV.ConcatenatedAddress AS 'Full Address',
DV.VALUE AS DisibilityName
FROM [MyPersonalSupport_reporting].[Mps].[Cases] AS CS
LEFT JOIN mps.CaseContracts AS CC ON CS.caseid = CC.caseid
LEFT JOIN mps.CaseStatusChangeHistories AS CSCH ON CS.CaseId = CSCH.CaseId
LEFT JOIN mps.Contacts AS CONTACT ON CS.CustomerId = CONTACT.ContactId
LEFT JOIN mps.ContactCurrentAddress AS CCAV ON CONTACT.ContactID = CCAV.ContactId
LEFT JOIN (SELECT EntityID, STRING_AGG(DV_VALUE,",") FROM dbo.disabilitiescrosstab GROUP BY EntityID) AS DV ON CONTACT.ContactId = DV.EntityID
WHERE
CSCH.Received >= '2000-01-01' AND CS.ServiceEndDate <= GETDATE()
AND CSCH.StatusId = 1392
AND CSCH.Archived = 0
AND CONTACT.Archived = 0
ORDER BY CS.CaseId
It appears that what you need is a two-part query. Once to get each "contact" person with their disabilities already pre-aggregated with all disabilities so the result is a single record per contact. THEN join with the cases. Additionally, you have FULL OUTER JOINS for your lookup tables. Its not like someone would be allowed to have multiple lookup values for ethnicity, sex, religion, sexuality -- would they? But in today's age of associating with things, possible? But I think the intent is that a person can only be classified into one category otherwise you would have multiple records for every combination of ethnicity, sexuality, transgender, etc... So, lets take the lookups as intended as only a single value would ever exist. These should just be INNER JOINS to the corresponding lookup table, not FULL OUTER joins.
Notice this query is nothing but associated with the contact and its corresponding lookup tables / disabilities and grouped by just the contact ID. So it will result in a single record no matter how many disablities per contact.
SELECT
CONTACT.ContactId,
max( CONTACT.FirstName ) 'Forename',
max( CONTACT.LastName ) 'Surname',
max( CONTACT.DateOfBirth ) DOB,
max( CONTACT.DateOfDeath ) DateOfDeath,
max( CONTACT.Age ) Age,
max( CCAV.ConcatenatedAddress ) 'Full Address',
max( LK1.Value ) Ethnicity,
max( LK2.Value ) Sex,
max( LK3.Value ) Religion,
max( LK4.Value ) Sexuality,
max( LK5.Value ) Transgender,
max( LK6.Value ) Nationality,
max( LK7.Value ) 'First Language',
max( CASE WHEN CONTACT.HasDisibility = 1 THEN 'YES' ELSE 'NO' END ) HasDisability,
max( CASE WHEN DV.value = 'Autistic Spectrum Condition' THEN 'YES' ELSE 'NO' END ) AutisticSpectrumCondition,
max( CASE WHEN DV.value = 'Hearing Impairment' THEN 'YES' ELSE 'NO' END ) 'Hearing Impairment',
max( CASE WHEN DV.value = 'Learning Disability' THEN 'YES' ELSE 'NO' END ) 'Learning Disability',
max( CASE WHEN DV.value = 'Mental Health' THEN 'YES' ELSE 'NO' END ) 'Mental Health',
max( CASE WHEN DV.value = 'Mobility Disability' THEN 'YES' ELSE 'NO' END ) 'Mobility Disability',
max( CASE WHEN DV.value = 'Progressive Disability / Chronic Illness' THEN 'YES' ELSE 'NO' END ) 'Progressive Disability / Chronic Illness',
max( CASE WHEN DV.value = 'Visual Impairment' THEN 'YES' ELSE 'NO' END ) 'Visual Impairment',
max( CASE WHEN DV.value = 'Other' THEN 'YES' ELSE 'NO' END ) 'Other Disability',
max( CASE WHEN DV.value = 'Does not wish to disclose' THEN 'YES' ELSE 'NO' END ) 'Does not wish to disclose'
FROM
mps.Contacts AS CONTACT
JOIN dbo.disabilitiescrosstab AS DV
ON CONTACT.ContactId = DV.EntityID
JOIN mps.ContactCurrentAddress AS CCAV
ON CONTACT.ContactID = CCAV.ContactId
JOIN mps.LookupItems AS LK1
ON CONTACT.EthnicityId = LK1.LookupItemId
JOIN mps.LookupItems AS LK2
ON CONTACT.SexId = LK2.LookupItemId
JOIN mps.LookupItems AS LK3
ON CONTACT.ReligionId = LK3.LookupItemId
JOIN mps.LookupItems AS LK4
ON CONTACT.SexualityId = LK4.LookupItemId
JOIN mps.LookupItems AS LK5
ON CONTACT.TransgenderId = LK5.LookupItemId
JOIN mps.LookupItems AS LK6
ON CONTACT.NationalityId = LK6.LookupItemId
JOIN mps.LookupItems AS LK7
ON CONTACT.FirstLanguageId = LK7.LookupItemId
WHERE
-- put the ARCHIVED FILTER HERE so it only includes active vs everyone in the system.
CONTACT.Archived = 0
GROUP BY
CONTACT.ContactId
Now, you can take the above query and use IT as a sub-select query to get its parts in the final
SELECT
SC.Name AS 'Sub-Contract',
CSCH.Received AS LiveDate,
CS.ServiceEndDate AS ServiceEndDate,
CS.CaseReference,
OneContact.Forename,
OneContact.Surname,
OneContact.DOB,
OneContact.DateOfDeath,
OneContact.Age,
OneContact.[Full Address],
OneContact.Ethnicity,
OneContact.Sex,
OneContact.Religion,
OneContact.Sexuality,
OneContact.Transgender,
OneContact.Nationality,
OneContact.[First Language],
SO.Name AS ServiceOffering,
LK.Value AS CaseStatus,
DATEDIFF(day, CSCH.Received, CS.serviceenddate) AS 'Days Occupied',
CONCAT (EMP.FirstName, ' ' , EMP.LastName) AS KeyWorker,
OneContact.HasDisability,
OneContact.AutisticSpectrumCondition,
OneContact.[Hearing Impairment],
OneContact.[Learning Disability],
OneContact.[Mental Health],
OneContact.[Mobility Disability],
OneContact.[Progressive Disability / Chronic Illness],
OneContact.[Visual Impairment],
OneContact.[Other Disability],
OneContact.[Does not wish to disclose]
FROM
Mps.Cases AS CS
INNER JOIN mps.CaseContracts AS CC
ON CS.caseid = CC.caseid
INNER JOIN mps.CaseStatusChangeHistories AS CSCH
ON CS.CaseId = CSCH.CaseId
INNER JOIN
( complete first query above) OneContact
ON CS.CustomerId = OneContact.ContactId
JOIN mps.LookupItems LK
ON CSCH.StatusId = LK.LookupItemId
JOIN mps.SubContracts SC
ON CC.SubContractId = SC.SubContractId
JOIN mps.ServiceOfferings SO
ON SC.ServiceOfferingId = SO.ServiceOfferingId
JOIN mps.Employees EMP
ON EMP.EmployeeId = CS.KeyWorkerId
WHERE
CSCH.Received >= '2000-01-01'
AND CS.ServiceEndDate <= GETDATE()
AND CSCH.StatusId = 1392
AND CSCH.Archived = 0
ORDER BY
CS.CaseId
Now, one suggestion for column names. I do not recommend having final column names with any spaces or special characters such as you have, especially with the ones like [Progressive Disability / Chronic Illness], and [Does not wish to disclose]. They should be normal, no spaces. The formatting / output should be handled by the output process to put in such headers and such. More headache when you need to explicitly tack quotes/brackets around column names, especially if you miss spaces. Instead, have column name as: ProgressiveDisabilityChronicIllness and ChronicIllness. Your output routines can split the column headings.
One additional point. The first query will process ALL contacts regardless of the cases. But the cases will only pull those that it qualifies for. If you find your query is taking too much time because of ALL contacts, you can update that by limiting the contacts by those cases it qualifies for. At least when querying the contacts, I did include the archived = 0 status there.

What is causing 'an item with the same key has already been added' error in ssrs?

I'm trying to run the following query for ssrs reporting services for a data portal in our Prophet 21 database (erp software from Epicor) and I'm running into some errors when trying to input the report in visual basic. I'm getting the following error:
TITLE: Microsoft SQL Server Report Designer
An error occurred while the query design method was being saved. An item with the same key has already been added.
BUTTONS:
OK
SELECT
inv_mast.item_desc,
oe_hdr.company_id,
oe_hdr.order_no,
oe_hdr.validation_status,
oe_hdr.order_date,
oe_hdr.requested_date,
oe_hdr.address_id,
oe_hdr.ship2_name,
oe_hdr.ship2_city,
oe_hdr.ship2_state,
oe_hdr_salesrep.salesrep_id,
p21_view_oe_line.line_no,
p21_view_oe_line.required_date
, inv_mast.item_id,
--p21_view_oe_line.qty_ordered,
p21_view_oe_line.unit_quantity,
p21_view_oe_line.unit_size,
p21_view_oe_line.qty_allocated,
p21_view_oe_line.qty_on_pick_tickets,
p21_view_oe_line.qty_invoiced,
p21_view_oe_line.qty_canceled,
p21_view_oe_line.unit_of_measure,
p21_view_oe_line.disposition,
p21_view_oe_line.unit_price,
CASE p21_view_oe_line.po_cost
WHEN 0 THEN
p21_view_oe_line.sales_cost ELSE
p21_view_oe_line.po_cost
END
oe_line_sales_cost,
po_hdr.supplier_id,
po_hdr.order_date,
po_line.date_due,
po_line.qty_ordered,
po_line.qty_received,
po_line.po_no,
po_hdr.po_class1,oe_hdr.customer_id,
customer.customer_name,
supplier.supplier_name,
oe_hdr.taker,
users.name
,contacts.first_name,
contacts.mi,
contacts.last_name,
p21_view_oe_line.pricing_unit,
p21_view_oe_line.pricing_unit_size,
p21_view_oe_line.qty_staged
, oe_hdr.location_id, location.location_name,
oe_hdr.completed,
oe_hdr.po_no,
customer.currency_id,
CASE WHEN customer.currency_id <> company.home_currency_id THEN
p21_view_oe_line.unit_price_home
END
unit_price_home,
CASE WHEN customer.currency_id <> company.home_currency_id THEN
CASE p21_view_oe_line.po_cost_home
WHEN 0 THEN
p21_view_oe_line.sales_cost_home
ELSE
p21_view_oe_line.po_cost_home
END END
oe_line_sales_cost_home,
company.home_currency_id,
CASE WHEN customer.currency_id <> company.home_currency_id THEN
( p21_view_oe_line.qty_ordered - p21_view_oe_line.qty_invoiced - p21_view_oe_line.qty_canceled - p21_view_oe_line.qty_staged ) * ( p21_view_oe_line.unit_price_home / p21_view_oe_line.pricing_unit_size )
END calc_open_price_home,
CASE WHEN customer.currency_id <> company.home_currency_id THEN
'Home : '
END currency_type
, CASE oe_hdr.job_control_flag
WHEN 'Y'
THEN oe_hdr.job_name
ELSE ''
END job_name,
oe_hdr.order_type,
p21_view_oe_line.user_line_no,
p21_view_prod_order_line_link.prod_order_number
--prod_order_hdr_ud.production_status
FROM oe_hdr
LEFT JOIN p21_view_oe_line ON p21_view_oe_line.order_no = oe_hdr.order_no
left join p21_view_prod_order_line_link ON p21_view_oe_line.oe_line_uid = p21_view_prod_order_line_link.transaction_uid
--left join prod_order_hdr_ud with (NOLOCK) ON p21_view_prod_order_line_link.prod_order_number = prod_order_hdr_ud.prod_order_number
left join prod_order_hdr with (NOLOCK) ON p21_view_prod_order_line_link.prod_order_number = prod_order_hdr.prod_order_number
LEFT JOIN company with (NOLOCK) ON company.company_id = oe_hdr.company_id
LEFT JOIN inv_mast with (NOLOCK) ON inv_mast.inv_mast_uid = p21_view_oe_line.inv_mast_uid
LEFT JOIN oe_hdr_salesrep with (NOLOCK) ON oe_hdr_salesrep.order_number = oe_hdr.order_no
LEFT JOIN contacts with (NOLOCK) ON contacts.id = oe_hdr_salesrep.salesrep_id LEFT JOIN customer ON customer.customer_id = oe_hdr.customer_id AND
customer.company_id = oe_hdr.company_id
LEFT JOIN users with (NOLOCK) ON users.id = oe_hdr.taker
LEFT JOIN location with (NOLOCK) ON location.location_id = oe_hdr.location_id
LEFT JOIN oe_line_po with (NOLOCK) LEFT JOIN po_hdr with (NOLOCK) ON po_hdr.po_no = oe_line_po.po_no
LEFT JOIN po_line with (NOLOCK) ON po_line.po_no = oe_line_po.po_no AND
po_line.line_no = oe_line_po.po_line_number
LEFT JOIN supplier with (NOLOCK) ON supplier.supplier_id = po_hdr.supplier_id
ON oe_line_po.order_number = oe_hdr.order_no AND
oe_line_po.line_number = p21_view_oe_line.line_no
AND
oe_line_po.delete_flag = 'N' AND
oe_line_po.cancel_flag = 'N' AND
oe_line_po.completed = 'N' AND
oe_line_po.connection_type = 'P'
WHERE
( oe_hdr_salesrep.primary_salesrep = 'Y' )
AND ( p21_view_oe_line.delete_flag = 'N' )
AND ( p21_view_oe_line.cancel_flag = 'N' )
AND ( p21_view_oe_line.complete = 'N') AND (( oe_hdr.completed <> 'Y') OR ((oe_hdr.completed = 'Y') ))
AND p21_view_oe_line.parent_oe_line_uid = '0'
AND (oe_hdr.rma_flag = 'N' )
AND ( oe_hdr.projected_order = 'N' )
--and (oe_hdr.order_type <> '1706')
--and (location_name = 'TriNova - Florida')
--AND prod_order_hdr.complete <> 'y'
-- and datediff(day , oe_hdr.order_date, getdate()) >= 5
-- AND ((oe_hdr.order_date + 5) < GETDATE())
-- AND (p21_view_audit_trail_oe_hdr_1319.date_created < dateadd(dd,5,p21_view_audit_trail_oe_hdr_1319.date_created))
--AND p21_view_audit_trail_oe_hdr_1319.date_created > GETDATE()
The errors is because you have two columns with the same name :
oe_hdr.order_date,
po_hdr.order_date,
You need to alias one of them
Same with
po_line.po_no,
oe_hdr.po_no,
Please ensure you format your code well so makes it easier to read
Easiest way to find them is to copy and paste your code into Notepad++ and double click on each column name.. notepad will highlight all instances of that word within the same document..

Excluding rows derived from case statement with a specific value based on values from another column

How do I exclude rows with a specific value in a field based on specific values of another field? To dive deeper:
I have a column called "rule_name" that's derived from a case statement.
I have another column called "DeliveryTermsIdentifier" that's pulled from another table (see image of query result below).
I'm trying to remove rows with rule_name "Delivery event required" only if DeliveryTermsIdentifier is "PP", "DA", ect. I'm getting thrown off because my rule_name column is based off a condition already.
image of query result
Here is the SQL used to derive those 2 columns:
,case when s.ShipmentNo is not null then cast(dqr.rulename as varchar(30))
else cast(dqc.dataqualityruleid as varchar(30)) end as rule_name
,case when (dqd.SuccessFlag = 0) then 'Missing'
when (dqd.SuccessFlag = 1) then 'Reported'
when (s.ShipmentNo is null) then 'Missing' end reporting_result
,s.DeliveryTermsIdentifier
from CustomerMasterList cml
join organization o on o.organizationid = cml.senderid
inner join DataQualityConfig dqc on dqc.DomainId = cml.DomainID
left outer join shipment s on s.shipmentno = cml.shipmentno
left outer join dataqualityresult dqd on dqd.shipmentid = s.shipmentid
left outer join dataqualityrule dqr on dqr.dataqualityruleid
=dqd.dataqualityruleid
One way is to put what you have in a subquery and filter out with a where clause in the outer query. E.g.
SELECT rule_name, reporting_result, DeliveryTermsIdentifier
FROM
(SELECT 'X'
,case when s.ShipmentNo is not null then cast(dqr.rulename as varchar(30))
else cast(dqc.dataqualityruleid as varchar(30)) end as rule_name
,case when (dqd.SuccessFlag = 0) then 'Missing'
when (dqd.SuccessFlag = 1) then 'Reported'
when (s.ShipmentNo is null) then 'Missing' end reporting_result
,s.DeliveryTermsIdentifier
from CustomerMasterList cml
join organization o on o.organizationid = cml.senderid
inner join DataQualityConfig dqc on dqc.DomainId = cml.DomainID
left outer join shipment s on s.shipmentno = cml.shipmentno
left outer join dataqualityresult dqd on dqd.shipmentid = s.shipmentid
left outer join dataqualityrule dqr on dqr.dataqualityruleid
=dqd.dataqualityruleid ) AS sub
WHERE DeliveryTermsIdentifier NOT IN ('PP', 'DA') AND rule_name <> 'Delivery event required'
You can also encapsulate your case statements into an outer apply and use the alias like this:
SELECT * ,
rules.rule_name ,
RESULT.reporting_result ,
s.DeliveryTermsIdentifier
FROM CustomerMasterList cml
JOIN organization o ON o.organizationid = cml.senderid
INNER JOIN DataQualityConfig dqc ON dqc.DomainId = cml.DomainID
LEFT OUTER JOIN shipment s ON s.shipmentno = cml.shipmentno
LEFT OUTER JOIN dataqualityresult dqd ON dqd.shipmentid = s.shipmentid
LEFT OUTER JOIN dataqualityrule dqr ON dqr.dataqualityruleid = dqd.dataqualityruleid
OUTER APPLY ( SELECT CASE WHEN ( dqd.SuccessFlag = 0 ) THEN 'Missing'
WHEN ( dqd.SuccessFlag = 1 ) THEN 'Reported'
WHEN ( s.ShipmentNo IS NULL ) THEN 'Missing'
END reporting_result ) RESULT
OUTER APPLY ( SELECT CASE WHEN s.ShipmentNo IS NOT NULL THEN
CAST(dqr.rulename AS VARCHAR(30))
ELSE
CAST(dqc.dataqualityruleid AS VARCHAR(30))
END AS rule_name ) rules
WHERE s.DeliveryTermsIdentifier NOT IN ( 'PP', 'DA' )
AND rules.rule_name <> 'Delivery event required';

SUM RESULTS OF CASE STATEMENTS

I've this query working fine. I need to have the sum of the column "piedini". Can you help me to undestand how to do? I obtain X row for each "Lunghezza" (lenght) that the query find. I'm not interested to this field but only to the sum o column "piedini" created from the CASE SUM.
SELECT
EXTRAMAG.PRS_LUNGHEZZA,SUM(RIGHEDOCUMENTI.QTAGEST) AS TAVOLI, CASE WHEN EXTRAMAG.PRS_LUNGHEZZA < '2000' THEN SUM(RIGHEDOCUMENTI.QTAGEST)*4 ELSE SUM(RIGHEDOCUMENTI.QTAGEST)*6 END AS PIEDINI
FROM dbo.TESTEDOCUMENTI
INNER JOIN dbo.ANAGRAFICACF
ON CODCLIFOR=CODCONTO
INNER JOIN dbo.RIGHEDOCUMENTI
ON PROGRESSIVO=IDTESTA AND TOTNETTORIGA <>'0' AND RIGHEDOCUMENTI.DESCRIZIONEART LIKE '%TAVOL%'
INNER JOIN dbo.EXTRAMAG
ON RIGHEDOCUMENTI.CODART=EXTRAMAG.CODART
LEFT JOIN .dbo.ANAGRAFICAAGENTI
ON CODAGENTE=CODAGENTE1
LEFT JOIN dbo.TABPAGAMENTI
ON CODPAGAMENTO = CODICE
WHERE dbo.TESTEDOCUMENTI.DOCCHIUSO = '0' AND dbo.TESTEDOCUMENTI.BLOCCATO = '0' AND dbo.TESTEDOCUMENTI.TIPODOC = 'ORC' AND TESTEDOCUMENTI.DATACONSEGNA BETWEEN DATEADD(DAY, -60, GETDATE()) AND GETDATE()
GROUP BY EXTRAMAG.PRS_LUNGHEZZA
Try the below :
select sum(PIEDINI) from (
SELECT XTRAMAG.PRS_LUNGHEZZA,SUM(RIGHEDOCUMENTI.QTAGEST) AS TAVOLI, CASE WHEN EXTRAMAG.PRS_LUNGHEZZA < '2000' THEN SUM(RIGHEDOCUMENTI.QTAGEST)*4 ELSE SUM(RIGHEDOCUMENTI.QTAGEST)*6 END AS PIEDINI
FROM dbo.TESTEDOCUMENTI
INNER JOIN dbo.ANAGRAFICACF
ON CODCLIFOR=CODCONTO
INNER JOIN dbo.RIGHEDOCUMENTI
ON PROGRESSIVO=IDTESTA AND TOTNETTORIGA <>'0' AND RIGHEDOCUMENTI.DESCRIZIONEART LIKE '%TAVOL%'
INNER JOIN dbo.EXTRAMAG
ON RIGHEDOCUMENTI.CODART=EXTRAMAG.CODART
LEFT JOIN .dbo.ANAGRAFICAAGENTI
ON CODAGENTE=CODAGENTE1
LEFT JOIN dbo.TABPAGAMENTI
ON CODPAGAMENTO = CODICE
WHERE dbo.TESTEDOCUMENTI.DOCCHIUSO = '0' AND dbo.TESTEDOCUMENTI.BLOCCATO = '0' AND dbo.TESTEDOCUMENTI.TIPODOC = 'ORC' AND TESTEDOCUMENTI.DATACONSEGNA BETWEEN DATEADD(DAY, -60, GETDATE()) AND GETDATE()
GROUP BY EXTRAMAG.PRS_LUNGHEZZA
)t

Order By Case multiple fields

The code below (and numerous codes like it) continues to return blanks.
Basically, if LaborCode = '01 - SC' then it should sort by JobSite, LaborCode, and Schedule (the exact date)
If it's NOT 01 - SC, it should sort by JobSite, LaborCode, and DayNo (the day of the week)
Select Distinct Agreements.AgrmntID, Agreements.Description, Agreements.Status,
JobSites.SiteName, JobSites.Address2, JobSites.City, Customers.CustName,
Customers.CompanyName, LaborCodeTypes.RepairCode As LaborCode, Schedule = Case
LaborCodeTypes.RepairCode
When '01 - SC' Then Left(Convert(varchar,AgreementSchedules.SchedDate,110),
10) Else DateName(dw, AgreementSchedules.SchedDate)
End, Employees1.EmpName As Vendor, Employees.EmpName As [Area Manager],
DatePart(dw, AgreementSchedules.SchedDate) As DayNo
From Agreements Inner Join
Customers On Agreements.CustID = Customers.CustID Inner Join
AgreementSchedules On Agreements.AgrmntID = AgreementSchedules.AgrmntID
Inner Join
JobSites On Agreements.CustSiteID = JobSites.CustSiteID Left Outer Join
LaborCodeTypes On AgreementSchedules.RepairID = LaborCodeTypes.RepairID
Left Outer Join
Employees On AgreementSchedules.FormanEmpID = Employees.EmployeeID Left Join
WorkOrderSchedules On WorkOrderSchedules.ScheduleID =
AgreementSchedules.ScheduleID And AgreementSchedules.ScheduleID =
WorkOrderSchedules.ScheduleID Left Join
WorkOrderScheduleTechs On WorkOrderSchedules.ScheduleID =
WorkOrderScheduleTechs.ScheduleID Left Join
Employees Employees1 On WorkOrderScheduleTechs.EmployeeID =
Employees1.EmployeeID
Where Agreements.Status = 2 And LaborCodeTypes.RepairCode <> 'Vendor Bill' And
Month(AgreementSchedules.SchedDate) = Month(GetDate())
Order By Case
When [LaborCodeTypes.RepairCode] In ('01 - SC') Then JobSites.SiteName +
LaborCodeTypes.RepairCode + Schedule
Else JobSites.SiteName + LaborCodeTypes.RepairCode + DayNo End
Thank you for your help!!
Try this:
ORDER BY JobSites.SiteName,
LaborCodeTypes.RepairCode,
CASE WHEN LaborCodeTypes.RepairCode IN ('01 - SC') THEN Schedule ELSE DayNo END
Okay, in SQL Server:
CREATE PROCEDURE dbo.Agreements_GetList
AS
BEGIN
SET NOCOUNT ON;
SELECT DISTINCT
a.AgrmntID,
a.Description,
a.Status,
js.SiteName,
js.Address2,
js.City,
c.CustName,
c.CompanyName,
LaborCode = lct.RepairCode,
Schedule = CASE lct.RepairCode
WHEN '01 - SC' THEN CONVERT(CHAR(10), aSch.SchedDate, 110)
--------------------^^^ much better than LEFT and not specifying length
ELSE DATENAME(WEEKDAY, aSch.SchedDate) END,
Vendor = e2.EmpName,
[Area Manager] = e1.EmpName,
DayNo = CONVERT(CHAR(1), DATEPART(WEEKDAY, aSch.SchedDate))
--------^^^ this convert is important
FROM dbo.Agreements AS a
INNER JOIN dbo.Customers AS c
ON a.CustID = c.CustID
INNER JOIN dbo.AgreementSchedules AS aSch
ON a.AgrmntID = aSch.AgrmntID
INNER JOIN dbo.JobSites AS js
ON a.CustSiteID = js.CustSiteID
LEFT OUTER JOIN dbo.LaborCodeTypes AS lct
ON aSch.RepairID = lct.RepairID
LEFT OUTER JOIN dbo.Employees AS e1
ON aSch.FormanEmpID = e1.EmployeeID
LEFT OUTER JOIN dbo.WorkOrderSchedules AS w
ON w.ScheduleID = aSch.ScheduleID
LEFT OUTER JOIN dbo.WorkOrderScheduleTechs AS wt
ON w.ScheduleID = wt.ScheduleID
LEFT OUTER JOIN dbo.Employees AS e2
ON wt.EmployeeID = e2.EmployeeID
WHERE
a.Status = 2
AND lct.RepairCode <> 'Vendor Bill'
AND aSch.SchedDate >= DATEADD(MONTH, 0, DATEDIFF(MONTH, 0, GETDATE()))
AND aSch.SchedDate < DATEADD(MONTH, 1, DATEDIFF(MONTH, 0, GETDATE()))
ORDER BY
js.SiteName,
lct.RepairCode,
CASE WHEN lct.RepairCode = '01 - SC'
THEN js.SiteName ELSE DayNo END;
END
GO
Now I have absolutely no knowledge of your application, so you will have to figure out how to call a stored procedure from it instead of embedding SQL.