SSRS: Getting "An item with the same key has already been added" - sql-server

Good afternoon, SO.
I'm trying to put my working SSMS query into SSRS, and I'm getting the mentioned error. I've looked over the code and I'm not seeing a multiple call, and so I came to you guys for help. I know it's long, and am more than willing to answer any questioned needed. I'm so lost.
Basically I need an overly convoluted join string (ugh, this program is going to be the bane of my existence). To gain provider data into the temp table I have to create (no physical way of making this without that)
/* These 2 below SELECTs pull the Group provider data only from Acuity which is output to #Temp_Group table */
SELECT DISTINCT provider.provider_identity
,provider_affiliation.db_record_id_parent
,provider_affiliation.db_record_id_child
,provider.external_provider_id
,provider.npi
,provider.provider_name
,provider.provider_type
,provider.tax_id
, db_record_parent.db_record_id
INTO #Temp
FROM provider AS provider
,provider AS provider2
,provider_affiliation
,db_record AS db_record_parent
,db_record AS db_record_child
WHERE (( provider.provider_identity = db_record_parent.key1 )
AND ( db_record_parent.db_record_id = provider_affiliation.db_record_id_parent )
AND ( provider2.provider_identity = db_record_child.key1 )
AND ( db_record_child.db_record_id = provider_affiliation.db_record_id_child )
AND (provider.provider_type = 'G')
AND (db_record_parent.table_code = 'PROV')
AND (provider2.provider_type <> 'G')
AND (db_record_child.table_code = 'PROV'))
AND provider.status = 'ACTV'
SELECT t.provider_identity
,t.db_record_id_parent
,t.db_record_id_child
,t.NPI
,t.provider_name
,t.provider_type
,dbo.address.address_1 AS [Billing Address]
,dbo.address.address_2 AS [Billing Suite]
,dbo.address.city AS [Billing City]
,dbo.state.state_code AS [Billing State]
,SUBSTRING(dbo.address.zip,1,5) AS [Billing ZIP]
,(CASE WHEN CHARINDEX('-', dbo.address.zip ) = 0
THEN ''
ELSE SUBSTRING(dbo.address.zip,(CHARINDEX('-', dbo.address.zip ) + 1),4)
END) AS [Billing ZIP Extension]
,dbo.telephony.telephony_string AS [Billing Phone]
,fax_tele.telephony_string AS [Billing Fax]
INTO #Temp_Group
FROM #Temp AS t
LEFT OUTER JOIN dbo.address_link
ON t.db_record_id = dbo.address_link.db_record_id
AND dbo.address_link.order_no = 1
LEFT OUTER JOIN dbo.address
ON dbo.address_link.address_identity = dbo.address.address_identity
LEFT OUTER JOIN dbo.db_record AS dbr_addr
ON dbo.address.address_identity = dbr_addr.key1
AND dbr_addr.table_code = 'ADDR'
LEFT OUTER JOIN dbo.state
ON dbo.address.state_identity = dbo.state.state_identity
LEFT OUTER JOIN dbo.telephony_link
ON t.db_record_id = dbo.telephony_link.db_record_id
AND dbo.telephony_link.order_no = 1
LEFT OUTER JOIN dbo.telephony
ON dbo.telephony_link.telephony_identity = dbo.telephony.telephony_identity
LEFT OUTER JOIN dbo.reason_reference AS rr_fax
ON rr_fax.reason_code = 'FAX'
AND rr_fax.reason_type = 'TT'
LEFT OUTER JOIN dbo.telephony_link AS fax_tell
ON t.db_record_id = fax_tell.db_record_id
AND fax_tell.telephony_type_identity = rr_fax.reason_reference_identity
AND fax_tell.order_no = (SELECT MIN(order_no) AS Expr1
FROM dbo.telephony_link AS fl
WHERE (db_record_id = t.db_record_id)
AND (telephony_type_identity = rr_fax.reason_reference_identity))
LEFT OUTER JOIN dbo.telephony AS fax_tele
ON fax_tell.telephony_identity = fax_tele.telephony_identity
/* Final Query that combines the provider and group records on the same row. This query is to provide Aetna a provider list of MP(Master Plan) plans */
SELECT DISTINCT dbo.person_name.last_name AS [Last Name], dbo.person_name.first_name AS [First Name], dbo.person_name.middle_name AS [Middle Name], CAST(dbo.person.birthdate AS DATE) AS DOB, dbo.person.sex AS Gender, dbo.person_name.name_suffix AS [Degree 1]
,NULL AS [Degree 2], NULL AS [Degree 3]
,(CASE WHEN tax.description = '' OR tax.description IS NULL
THEN tax.description
WHEN tax.description IN ('General Practice','General Dentist','Dentist')
THEN 'PCP'
ELSE 'Specialist'
END) AS Role
,tax.description AS [Specialty 1]
,(CASE WHEN udf.user_field_data_14 > ' ' AND udf.user_field_data_14 <> 'NA'
THEN 'Y'
ELSE 'N'
END) AS [Board Cert]
,NULL AS [Effective Date]
,REPLACE(CONVERT (VARCHAR(10), udf.user_field_data_15, 101), '/', '') AS [Expiration Date]
,udf.user_field_data_14 AS [Specialty 1 Board Name]
,NULL AS [Specialty 2], NULL AS [Board Cert (Y/N)], NULL AS [Effective Date], NULL AS [Expiration Date], NULL AS [Specialty 2 Board Name]
,NULL AS [Specialty 3], NULL AS [Board Cert (Y/N)], NULL AS [Effective Date], NULL AS [Expiration Date], NULL AS [Specialty 3 Board Name]
,(CASE WHEN rr_l.description <> 'English'
THEN rr_l.description
ELSE NULL
END) AS Language
,NULL AS [Medical School], NULL AS [Grad Year]
,udf.user_field_data_10 AS [Medicare #], NULL AS [Medicare Exp Date]
,REPLACE(CONVERT (VARCHAR(10), udf.user_field_data_30, 101), '/', '') AS [CDS Exp Date]
,udf.user_field_data_13 AS [CDS Number]
,udf.user_field_data_12 AS DEA, REPLACE(CONVERT (VARCHAR(10), udf.user_field_data_18, 101), '/', '') AS [DEA Exp]
,COALESCE(vpl.state,NULL) AS [License State of Issue]
,udf.user_field_data_11 AS [State Lic #], REPLACE(CONVERT (VARCHAR(10), udf.user_field_data_17, 101), '/', '') AS [State Lic Exp]
,udf.user_field_data_09 AS [Medicaid #],NULL AS [Medicaid Expiration Date],NULL AS [Medicaid State]
,NULL AS [Public Email], dbo.telephony.telephony_string AS [NPI Phone Number], dbo.provider.NPI AS [NPI Number (Type 1)]
--,COALESCE(vppa.privilege_provider1_name, NULL) AS [Hospital Affiliation Name 1]
,vppa.privilege_provider1_name AS [Hospital Affiliation Name 1]
,NULL AS [Hospital Affiliation Name 2]
,NULL AS [Hospital Affiliation Name 3]
,dbo.person_id_key.id_key AS SSN, dbo.provider.tax_id, NULL AS [TIN Owner], dbo.provider.provider_name AS [Group Name]
,t2.NPI AS [NPI Number (Type II)]
,'' AS [Does this NPI apply to all Service Locations and Billing Addresses for this Tax id?]
,'' AS [Does this NPI apply to all providers using this Tax id?]
,'' AS [Does this NPI apply to all Service Locations and Billing Addresses for this provider only?]
,'' AS [Does this NPI apply to all to all tax ids for this provider only?]
,dbo.address.address_1 AS [Service Address],dbo.address.address_2 AS [Service Suite],dbo.address.city AS [Service City], dbo.state.state_code AS [Service State], SUBSTRING(dbo.address.zip,1,5) AS [Service ZIP]
,(CASE WHEN CHARINDEX('-', dbo.address.zip ) = 0
THEN ''
ELSE SUBSTRING(dbo.address.zip,(CHARINDEX('-', dbo.address.zip ) + 1),4)
END) AS [Service ZIP Extension]
,dbo.telephony.telephony_string AS [Service Phone], fax_tele.telephony_string AS [Service Fax]
,(udf.user_field_data_01 + '|' + udf.user_field_data_02 + '|' + udf.user_field_data_03 + '|' + udf.user_field_data_04 + '|' + udf.user_field_data_05 + '|' + udf.user_field_data_06 + '|' + udf.user_field_data_07) AS [Office Hours]
,NULL AS [Practice Age Limitations]
,udf2.user_field_data_03 AS [Accepting New Patients]
,udf2.user_field_data_02 AS [Directory Print]
,t2.[Billing Address]
,t2.[Billing Suite]
,t2.[Billing City]
,t2.[Billing State]
,t2.[Billing ZIP]
,t2.[Billing ZIP Extension]
,t2.[Billing Phone]
,t2.[Billing Fax]
,REPLACE(CONVERT (VARCHAR(10), dbo.address_link.start_date, 101), '/', '') AS [Network TIN/Service Location Effective Date]
,REPLACE(CONVERT (VARCHAR(10), dbo.address_link.end_date, 101), '/', '') AS [Network TIN/Service Location Term Date]
,CAST(udf.user_field_data_26 AS DATE) AS [Original Credential Date]
,CAST(udf.user_field_data_27 AS DATE) AS [Recredential Date]
,(CASE WHEN udf.user_field_data_21 = udf.user_field_data_26
THEN ''
ELSE CAST(udf.user_field_data_21 AS DATE)
END) AS [Most Recent Recredentialing Date]
,NULL AS [PEARL-HAMP Provider?]
,company.company_code
,company.description
,dbo.address.additional_loc
,dbr_addr.db_record_id AS db_record_id_addr
,dbo.provider.external_provider_id, dbo.db_record.active_flag,dbo.provider.provider_type
,dbo.provider.provider_identity
,db_record.db_record_id
,db_record.key1
,db_record.linking_id
,db_record.record_template_library_identity
,db_record.calling_db_record_id
,db_record.parent_db_record_id
,t2.db_record_id_parent
,t2.provider_identity
FROM dbo.provider
LEFT OUTER JOIN dbo.db_record
ON dbo.provider.provider_identity = dbo.db_record.key1
AND dbo.db_record.table_code = 'PROV'
-- For Group provider data (Billing Address fields) joining to a regular Provider record
LEFT OUTER JOIN [#Temp_Group] AS t2
ON t2.db_record_id_child = dbo.db_record.db_record_id
-- Next 3 Joins needed to access company.company_code and to pull MP records (Dental Master Plan)
LEFT OUTER JOIN dbo.provider_affiliation praf
ON praf.db_record_id_child = dbo.db_record.db_record_id
LEFT OUTER JOIN dbo.db_record AS dbr_parent
ON praf.db_record_id_parent = dbr_parent.db_record_id
LEFT OUTER JOIN company
ON dbr_parent.key1 = company.company_identity
-- For 'Accepting New Patients' and 'Directory Print' Flags code (Found on the Provider Network tab in Acuity)
LEFT OUTER JOIN v_provider_network_affiliation vpna
ON vpna.key2 = dbo.provider.provider_identity
AND vpna.key1 = '280'
LEFT OUTER JOIN user_field_data AS udf2
ON udf2.table_code='PRNW'
AND udf2.key1=vpna.provider_affiliation_identity
--Service Address fields (Regular provider records level)
LEFT OUTER JOIN dbo.address_link
ON dbo.db_record.db_record_id = dbo.address_link.db_record_id
AND dbo.address_link.order_no = 1
LEFT OUTER JOIN dbo.address
ON dbo.address_link.address_identity = dbo.address.address_identity
LEFT OUTER JOIN dbo.db_record AS dbr_addr
ON dbo.address.address_identity = dbr_addr.key1
AND dbr_addr.table_code = 'ADDR'
LEFT OUTER JOIN dbo.state
ON dbo.address.state_identity = dbo.state.state_identity
LEFT OUTER JOIN dbo.reason_reference AS rr_country
ON dbo.address.country_identity = rr_country.reason_reference_identity
LEFT OUTER JOIN dbo.reason_reference AS rr_region
ON dbo.address.region_identity = rr_region.reason_reference_identity
LEFT OUTER JOIN dbo.telephony_link
ON dbo.db_record.db_record_id = dbo.telephony_link.db_record_id
AND dbo.telephony_link.order_no = 1
LEFT OUTER JOIN dbo.telephony
ON dbo.telephony_link.telephony_identity = dbo.telephony.telephony_identity
LEFT OUTER JOIN dbo.reason_reference AS rr_fax
ON rr_fax.reason_code = 'FAX'
AND rr_fax.reason_type = 'TT'
LEFT OUTER JOIN dbo.telephony_link AS fax_tell
ON dbo.db_record.db_record_id = fax_tell.db_record_id
AND fax_tell.telephony_type_identity = rr_fax.reason_reference_identity
AND fax_tell.order_no = (SELECT MIN(order_no) AS Expr1
FROM dbo.telephony_link AS fl
WHERE (db_record_id = dbo.db_record.db_record_id)
AND (telephony_type_identity = rr_fax.reason_reference_identity))
LEFT OUTER JOIN dbo.telephony AS fax_tele
ON fax_tell.telephony_identity = fax_tele.telephony_identity
LEFT OUTER JOIN dbo.reason_reference AS rr_telephony
ON dbo.telephony_link.telephony_type_identity = rr_telephony.reason_reference_identity
LEFT OUTER JOIN dbo.provider_language
ON dbo.provider_language.provider_identity = dbo.provider.provider_identity
AND dbo.provider_language.order_no = 1
LEFT OUTER JOIN dbo.users AS u_entry
ON dbo.provider.entry_by = u_entry.user_identity
LEFT OUTER JOIN dbo.users AS u_mod
ON dbo.provider.mod_by = u_mod.user_identity
LEFT OUTER JOIN dbo.reason_reference AS rr_l
ON dbo.provider_language.language_identity = rr_l.reason_reference_identity
LEFT OUTER JOIN dbo.person_name
ON dbo.provider.person_identity = dbo.person_name.person_identity
AND dbo.person_name.order_no = 1
LEFT OUTER JOIN dbo.person
ON dbo.person.person_identity = dbo.provider.person_identity
LEFT OUTER JOIN dbo.person_id_key
ON dbo.person_id_key.person_identity = dbo.person.person_identity
AND dbo.person_id_key.order_no = 1
LEFT OUTER JOIN dbo.id_key_type
ON dbo.id_key_type.id_key_type_identity = dbo.person_id_key.id_key_type_identity
LEFT OUTER JOIN dbo.user_field_data udf
ON provider.provider_identity = udf.key1
AND udf.table_code = 'PROV'
LEFT OUTER JOIN dbo.provider_taxonomy prvt
ON prvt.provider_identity = dbo.provider.provider_identity
INNER JOIN dbo.taxonomy tax
ON tax.taxonomy_identity = prvt.taxonomy_identity
-- For Hospital Affil. Name
LEFT OUTER JOIN v_provider_privilege_affiliation AS vppa
ON vppa.provider2_identity = dbo.provider.provider_identity
-- For License State of Issue
LEFT OUTER JOIN v_provider_license AS vpl
ON vpl.provider_identity = dbo.provider.provider_identity
WHERE dbo.db_record.active_flag = 'Y'
AND company.company_code in ('Prestige', '114', '115', '148', '181')
ORDER BY dbo.provider.NPI

As #Jacob said, you have multiple fields with the same name: [Effective Date], [Board Cert (Y/N)]. While SSMS can handle this if you run the query, SSRS must have uniquely named columns so it knows what to put into each field of the report. One thing I started doing is putting the alias first, so instead of
dbr_addr.db_record_id AS db_record_id_addr
I would put
db_record_id_addr = dbr_addr.db_record_id
That nicely lines up all of the column names so they're easy to see.

Related

how to concatenate text from multiable rows in SSRS?

I got introduced to SSRS recently and I am facing a problem in extracting data from the database.
I searched online and I found out that this is called concatenate text from multiable rows. Now, I tried a code.. but in the results, it give me the data duplicated next to each other separated by a comma. Now I am happy that it is separating the result with a coma... but why giving me the data duplicated?
The Code:
select distinct wm1.Date, p1.[Medical Record Number], Wound_Type =CONCAT
((
select distinct CAST(wt2.Name as VARCHAR(MAX))+ ' /// ' from dbo.[Wound Type] as wt2
inner join dbo.[Wound Management] as wm2 on wm2.[Wound Type_ID] = wt2.ID
inner join dbo.Patient as p2 on wm2.[Owner (Patient)_Patient_ID]=p2.ID
where wm1.Date=wm2.Date
FOR XML PATH('')
),wt1.Name)
from dbo.[Wound Type] as wt1
inner join dbo.[Wound Management] as wm1 on wm1.[Wound Type_ID] = wt1.ID
inner join dbo.Patient as p1 on wm1.[Owner (Patient)_Patient_ID]=p1.ID
group by wm1.Date, wt1.Name, p1.[Medical Record Number]
the result:
Please Help.
Your data is duplicated because you are CONCATing the list of wt2.Names with the wt1.Name - ,wt1.Name). The one with NULL date isn't finding a matching record and is only showing the wt1.Name
Actually I think you may want to use the STUFF function instead of CONCAT to remove any extra slashes at the end.
SELECT DISTINCT wm1.Date, p1.[Medical Record Number], Wound_Type = STUFF(
(
SELECT DISTINCT ' /// ' + CAST(wt2.Name as VARCHAR(MAX))
from dbo.[Wound Type] as wt2
inner join dbo.[Wound Management] as wm2 on wm2.[Wound Type_ID] = wt2.ID
inner join dbo.Patient as p2 on wm2.[Owner (Patient)_Patient_ID]=p2.ID
where wm1.Date=wm2.Date
FOR XML PATH('')
), 1, 5, '' )
from dbo.[Wound Type] as wt1
inner join dbo.[Wound Management] as wm1 on wm1.[Wound Type_ID] = wt1.ID
inner join dbo.Patient as p1 on wm1.[Owner (Patient)_Patient_ID]=p1.ID
group by wm1.Date, wt1.Name, p1.[Medical Record Number]
This doesn't fix that NULL date issue. You could wrap the STUFF in an ISNULL.
SELECT DISTINCT wm1.Date, p1.[Medical Record Number], Wound_Type = ISNULL(STUFF(
(
SELECT DISTINCT ' /// ' + CAST(wt2.Name as VARCHAR(MAX))
from dbo.[Wound Type] as wt2
inner join dbo.[Wound Management] as wm2 on wm2.[Wound Type_ID] = wt2.ID
inner join dbo.Patient as p2 on wm2.[Owner (Patient)_Patient_ID]=p2.ID
where wm1.Date=wm2.Date
FOR XML PATH('')
), 1, 5, '' )
, wt1.Name)
from dbo.[Wound Type] as wt1
inner join dbo.[Wound Management] as wm1 on wm1.[Wound Type_ID] = wt1.ID
inner join dbo.Patient as p1 on wm1.[Owner (Patient)_Patient_ID]=p1.ID
group by wm1.Date, wt1.Name, p1.[Medical Record Number]
Here's an explanation of stuff:
How Stuff and 'For Xml Path' work in SQL Server?

Get Results of Two Datasets Without UNION

I am writing a stored procedure to retrieve purchases out of Microsoft Great Plains so they can be processed.
Great Plains has two invoice table sets of note. SOP10100/SOP10200 contain the invoice header and details of an invoice that has not yet been posted. SOP30200/SOP30300 contain the invoice header and details of invoices that have been posted. When a product is purchased, it immediately goes into SOP10100/SOP10200, and once it is posted, it is moved from SOP10100/SOP10200 to SOP30200/SOP30300. There is a common table SOP10106 that contains user-defined fields and can be joined to either table set.
When pulling purchases, we need to check both tables in case an invoice gets posted before it can be processed. Up until now, the only way we've been able to achieve this is through a UNION, which is basically two identical queries with the difference being that one joins to SOP10100/SOP10200 and the other joins to SOP30200/SOP30300.
I'm hoping to find a way that we can pare this down into a single query (utilizing the shared SOP10106 table) to hopefully get one result set that only contains the records that have either a SOP10100/SOP10200 or SOP30200/SOP30300 record. The join to the GP tables is within the OPENQUERY function.
The SPROC is below:
SELECT [Account1].AccountID, [Account1].AccountNumber AS 'Order_OrgID', [Account2].AccountNumber AS 'CI_OrgID', [Contact].cncy_CustomerNumber AS 'CustomerID', [Contact].EMailAddress1 AS 'Email', [Contact].FirstName, [Contact].LastName, [StringMapMarket].Value AS 'Market',
GP.Invoice, GP.SKU, MAP.Name, GP.OrderDate, GP.Quantity, GP.SLPRSNID, RTRIM(GP.SKU) + '-' + [StringMapMarket].Value COLLATE DATABASE_DEFAULT as AdjSku, MAP.CourseID, MAP.SubscriptionID
FROM OPENQUERY(GPSERVER, 'SELECT [SOP10100].SOPNUMBE AS Invoice, [SOP10200].ITEMNMBR AS SKU, [SOP10200].ITEMDESC AS Product, [SOP10100].CREATDDT AS OrderDate, [SOP10200].QTYORDER AS Quantity,
[SOP10100].SLPRSNID, [SOP10100].CUSTNMBR, [SOP10106].USERDEF1, [SOP10100].SOPTYPE, [SOP10100].VOIDSTTS
FROM CPI.dbo.SOP10100 WITH (NOLOCK)
INNER JOIN CPI.dbo.SOP10200 WITH (NOLOCK) ON [SOP10100].SOPNUMBE = [SOP10200].SOPNUMBE AND [SOP10100].CREATDDT > DATEADD(ww,-4,GETDATE())
INNER JOIN CPI.dbo.SOP10106 WITH (NOLOCK) ON [SOP10100].SOPNUMBE = [SOP10106].SOPNUMBE WHERE [SOP10200].SOPTYPE = 3
AND [SOP10100].VOIDSTTS <> 1
AND NOT [SOP10106].USERDEF1 = ''INTERNAL LMS''') as GP
INNER JOIN [CRMSERVER].CPI_MSCRM.dbo.Account AS [Account1] WITH(NOLOCK) ON GP.CUSTNMBR = [Account1].AccountNumber COLLATE DATABASE_DEFAULT
INNER JOIN [CRMSERVER].CPI_MSCRM.dbo.Contact WITH(NOLOCK) ON GP.USERDEF1 = [Contact].cncy_customernumber COLLATE DATABASE_DEFAULT
INNER JOIN [CRMSERVER].CPI_MSCRM.dbo.Account AS [Account2] WITH(NOLOCK) ON [Contact].ParentCustomerId = [Account2].Id
INNER JOIN CPIProcessData.dbo.StringMap AS [StringMapMarket] WITH(NOLOCK) ON [Account1].cncy_MarketType = [StringMapMarket].AttributeValue AND [StringMapMarket].AttributeName = 'cncy_MarketType' AND [StringMapMarket].ObjectTypeCode = 2
INNER JOIN CPIProcessData.dbo.StringMap AS [StringMapCountry] WITH(NOLOCK) ON [Contact].cncy_address1country = [StringMapCountry].AttributeValue AND [StringMapCountry].AttributeName = 'cncy_address1country' AND [StringMapMarket].ObjectTypeCode = 2
INNER JOIN CPIProcessData.dbo.vwLmsMapping AS MAP WITH(NOLOCK) ON MAP.Subscription = 'true' AND
CASE
WHEN [StringMapCountry].Value IN ('US','Canada') THEN RTRIM(GP.SKU) + '-' +
CASE
WHEN [StringMapMarket].Value IN ('HE','MH') THEN 'HE'
WHEN [StringMapMarket].Value IN ('ED') THEN 'ED'
ELSE 'HS'
END
ELSE RTRIM(GP.SKU)
END = map.SKU
LEFT OUTER JOIN SeatLog WITH(NOLOCK) ON GP.Invoice = [SeatLog].Invoice AND RTRIM(GP.SKU) = [SeatLog].SKU
WHERE GP.SOPTYPE = 3
AND GP.VOIDSTTS <> 1
AND NOT GP.USERDEF1 = 'INTERNAL LMS'
AND [SubscriptionLog].ID IS NULL
UNION
SELECT [Account1].AccountID, [Account1].AccountNumber AS 'Order_OrgID', [Account2].AccountNumber AS 'CI_OrgID', [Contact].cncy_CustomerNumber AS 'CustomerID', [Contact].EMailAddress1 AS 'Email', [Contact].FirstName, [Contact].LastName, [StringMapMarket].Value AS 'Market',
GP.Invoice, GP.SKU, MAP.Name, GP.OrderDate, GP.Quantity, GP.SLPRSNID, RTRIM(GP.SKU) + '-' + [StringMapMarket].Value COLLATE DATABASE_DEFAULT as AdjSku, MAP.CourseID, MAP.SubscriptionID
FROM OPENQUERY(GPSERVER, 'SELECT [SOP30200].SOPNUMBE AS Invoice, [SOP30300].ITEMNMBR AS SKU, [SOP30300].ITEMDESC AS Product, [SOP30200].CREATDDT AS OrderDate, [SOP30300].QTYORDER AS Quantity,
[SOP30200].SLPRSNID, [SOP30200].CUSTNMBR, [SOP10106].USERDEF1, [SOP30200].SOPTYPE, [SOP30200].VOIDSTTS
FROM CPI.dbo.SOP30200 WITH (NOLOCK)
INNER JOIN CPI.dbo.SOP30300 WITH (NOLOCK) ON [SOP30200].SOPNUMBE = [SOP30300].SOPNUMBE AND [SOP30200].CREATDDT > DATEADD(ww,-4,GETDATE())
INNER JOIN CPI.dbo.SOP10106 WITH (NOLOCK) ON [SOP30200].SOPNUMBE = [SOP10106].SOPNUMBE WHERE [SOP30300].SOPTYPE = 3
AND [SOP30200].VOIDSTTS <> 1
AND NOT [SOP10106].USERDEF1 = ''INTERNAL LMS''') as GP
INNER JOIN [CRMSERVER].CPI_MSCRM.dbo.Account AS [Account1] WITH(NOLOCK) ON GP.CUSTNMBR = [Account1].AccountNumber COLLATE DATABASE_DEFAULT
INNER JOIN [CRMSERVER].CPI_MSCRM.dbo.Contact WITH(NOLOCK) ON GP.USERDEF1 = [Contact].cncy_customernumber COLLATE DATABASE_DEFAULT
INNER JOIN [CRMSERVER].CPI_MSCRM.dbo.Account AS [Account2] WITH(NOLOCK) ON [Contact].ParentCustomerId = [Account2].Id
INNER JOIN CPIProcessData.dbo.StringMap AS [StringMapMarket] WITH(NOLOCK) ON [Account1].cncy_MarketType = [StringMapMarket].AttributeValue AND [StringMapMarket].AttributeName = 'cncy_MarketType' AND [StringMapMarket].ObjectTypeCode = 2
INNER JOIN CPIProcessData.dbo.StringMap AS [StringMapCountry] WITH(NOLOCK) ON [Contact].cncy_address1country = [StringMapCountry].AttributeValue AND [StringMapCountry].AttributeName = 'cncy_address1country' AND [StringMapMarket].ObjectTypeCode = 2
INNER JOIN CPIProcessData.dbo.vwLmsMapping AS MAP WITH(NOLOCK) ON MAP.Subscription = 'true' AND
CASE
WHEN [StringMapCountry].Value IN ('US','Canada') THEN RTRIM(GP.SKU) + '-' +
CASE
WHEN [StringMapMarket].Value IN ('HE','MH') THEN 'HE'
WHEN [StringMapMarket].Value IN ('ED') THEN 'ED'
ELSE 'HS'
END
ELSE RTRIM(GP.SKU)
END = map.SKU
LEFT OUTER JOIN SeatLog WITH(NOLOCK) ON GP.Invoice = [SeatLog].Invoice AND RTRIM(GP.SKU) = [SeatLog].SKU
WHERE GP.SOPTYPE = 3
AND GP.VOIDSTTS <> 1
AND NOT GP.USERDEF1 = 'INTERNAL LMS'
AND [SubscriptionLog].ID IS NULL
Does anyone know of any ideas to simplify this without having to use a UNION? I'm hoping to improve the performance.
I tried to do it a different way by using FULL JOIN and COALESCE as follows:
SELECT COALESCE(Table1.SOPNUMBE, Table2.SOPNUMBE) AS 'SOPNUMBE', COALESCE(Table1.ITEMNMBR, Table2.ITEMNMBR) AS 'SKU', COALESCE(Table1.CUSTNMBR, Table2.CUSTNMBR) AS 'Account_Number', [SubscriptionLog].ID
FROM (SELECT SOP10100.SOPNUMBE,SOP10200.ITEMNMBR,SOP10100.CUSTNMBR FROM [GPSERVER].CPI.dbo.SOP10100 INNER JOIN [GPSERVER].CPI.dbo.SOP10200 ON SOP10100.SOPNUMBE = SOP10200.SOPNUMBE) AS Table1
FULL JOIN (SELECT SOP30200.SOPNUMBE,SOP30300.ITEMNMBR,SOP30200.CUSTNMBR FROM [GPSERVER].CPI.dbo.SOP30200 INNER JOIN [GPSERVER].CPI.dbo.SOP30300 ON SOP30200.SOPNUMBE = SOP30300.SOPNUMBE) AS Table2 ON Table1.SOPNUMBE = Table2.SOPNUMBE AND Table1.ITEMNMBR = Table2.ITEMNMBR AND Table1.CUSTNMBR = Table2.CUSTNMBR
INNER JOIN [GPSERVER].CPI.dbo.SOP10106 WITH(NOLOCK) ON COALESCE(Table1.SOPNUMBE, Table2.SOPNUMBE) = SOP10106.SOPNUMBE
INNER JOIN [CRMSERVER].CPI_MSCRM.dbo.Account AS [Account1] WITH(NOLOCK) ON COALESCE(Table1.CUSTNMBR, Table2.CUSTNMBR) = [Account1].AccountNumber COLLATE DATABASE_DEFAULT
INNER JOIN [CRMSERVER].CPI_MSCRM.dbo.Contact WITH(NOLOCK) ON SOP10106.USERDEF1 = [Contact].cncy_customernumber COLLATE DATABASE_DEFAULT
--INNER JOIN [CRMSERVER].CPI_MSCRM.dbo.Account AS [Account2] WITH(NOLOCK) ON [Contact].ParentCustomerId = [Account2].Id
INNER JOIN CPIProcessData.dbo.StringMap AS [StringMapMarket] WITH(NOLOCK) ON [Account1].cncy_MarketType = [StringMapMarket].AttributeValue AND [StringMapMarket].AttributeName = 'cncy_MarketType' AND [StringMapMarket].ObjectTypeCode = 2
INNER JOIN CPIProcessData.dbo.StringMap AS [StringMapCountry] WITH(NOLOCK) ON [Contact].cncy_address1country = [StringMapCountry].AttributeValue AND [StringMapCountry].AttributeName = 'cncy_address1country' AND [StringMapMarket].ObjectTypeCode = 2
INNER JOIN CPIProcessData.dbo.vwLmsMapping AS MAP WITH(NOLOCK) ON MAP.Subscription = 'true' AND
CASE
WHEN [StringMapCountry].Value IN ('US','Canada') THEN RTRIM(COALESCE(Table1.ITEMNMBR, Table2.ITEMNMBR)) + '-' +
CASE
WHEN [StringMapMarket].Value IN ('HE','MH') THEN 'HE'
WHEN [StringMapMarket].Value IN ('ED') THEN 'ED'
ELSE 'HS'
END
ELSE RTRIM(COALESCE(Table1.ITEMNMBR, Table2.ITEMNMBR))
END = map.SKU
LEFT OUTER JOIN [SubscriptionLog] WITH(NOLOCK) ON SOP10106.SOPNUMBE = [SubscriptionLog].Invoice AND RTRIM(COALESCE(Table1.ITEMNMBR, Table2.ITEMNMBR)) = [SubscriptionLog].SKU
WHERE [SubscriptionLog].ID IS NULL
It seems to run a little better, but it returns duplicates and not the results I expect.

Order By being ignored in SQL Server 2008 with multiple subqueries

I have a report that returns a list of visits made by a patient however the order of visits is completely scrambled. The list of visits is obtained within a subquery like so:
INNER JOIN (SELECT subject_id,
A.id [VisitID],
A.visit_schedule_id [VisitScheduleID],
B.client_visit_description [Visit],
visit_date_local [Visit Date],
call_date [Call Date]
FROM tbl_visit A
INNER JOIN tbl_visit_schedule B ON B.id = A.visit_schedule_id) F
There is an inner query that uses this "F" block to grab relevant values to display to the end-user like so:
SELECT TOP 9999999999
A.[name] [Country Name],
B.[site_number] [Site Number],
D.[investigator_name] [Investigator Name],
C.[spid] [Patient Number],
E.[YOB] [Year of Birth],
F.[Visit] [Visit],
CONVERT(NVARCHAR, F.[Visit Date], 120) [Visit Date],
ISNULL(pl.[Pack(s) Assigned], 'N/A') [Kit Assigned],
H.[Confirmation (doc)]
FROM (
And finally there is an outer select which displays to the user:
SELECT DISTINCT
[Country Name],
[Investigator Name],
[Patient Number],
[Year of Birth],
--[Visit],
[Visit Date],
[Kit Assigned],
[Confirmation (doc)]
FROM (
I have an ORDER BY for the inner select statement that looks like this:
ORDER BY CAST(F.[Visit Date] AS DATE) asc, F.[Call Date] asc
The issue is that when I have everything displaying ('Visit' isn't commented out) SQL returns the results in an un-ordered manner, even with the order by at the end. If I comment out Visit however, the results begin to order.
I'm not sure what significance this one particular column has on the rest of the report that is causing order by to fail, does anyone else have any clues on the matter?
Update: here's the entire query:
SELECT DISTINCT site_id, site_number,
[Country Name],
[Investigator Name],
[Patient Number],
[Year of Birth],
[Visit],
[Visit Date],
[Kit Assigned],
[Confirmation (doc)]
FROM (SELECT TOP 99999999999
B.[id] [site_id],
B.[site_number] [site_number],
A.[name] [Country Name],
B.[site_number] [Site Number],
B.[site_number] [SiteNumber],
D.[investigator_name] [Investigator Name],
C.[spid] [Patient Number],
E.[YOB] [Year of Birth],
F.[Visit] [Visit],
CONVERT(NVARCHAR, F.[Visit Date], 120) [Visit Date],
ISNULL(pl.[Pack(s) Assigned], 'N/A') [Kit Assigned],
H.[Confirmation (doc)]
FROM (
SELECT [id],
[name],
[code] [country_code]
FROM [dbo].[tbl_country]) A
INNER JOIN [dbo].[tbl_site] B
ON A.[id] = B.[country_id]
INNER JOIN [dbo].[tbl_subject] C
ON B.[id] = C.[site_id]
LEFT JOIN (SELECT A.id,
A.inv_first_name + ' ' + A.inv_last_name
[investigator_name]
FROM vw_site A) D
ON B.[id] = D.[id]
INNER JOIN (SELECT A.[subject_id],
B.int_value [YOB]
FROM vw_subject_info A
INNER JOIN tbl_custom_data B
ON B.row_id = A.subject_id
AND B.table_name = 'Subject'
AND B.[field_name] = 'Initial_DOB')
E
ON C.[id] = E.[subject_id]
INNER JOIN (
SELECT subject_id,
VisitID,
VisitScheduleID,
site_id,
site_number,
visit [Visit],
visit_date_local [Visit Date],
call_date [Call Date]
FROM vw_visit
) F
ON C.[id] = F.[subject_id]
LEFT JOIN (SELECT [visit_id],
[int_value] [Confirmation (doc)]
FROM [vw_visitDetail]
WHERE [field_name] = 'docId'
) H
ON F.[VisitID] = H.[visit_id]
--Selecting the packs dispensed at latest dispensing visit
LEFT JOIN (SELECT A.[id] [visit_id],
STUFF((SELECT ', ' + CAST(C.[client_pack_number] AS NVARCHAR(MAX))
FROM [dbo].[tbl_visit_pack] B
INNER JOIN [dbo].[tbl_pack] C
ON B.[pack_id] = C.[id]
INNER JOIN dbo.tbl_pack_type pt
ON pt.id = c.pack_type_id
WHERE A.[id] = B.[visit_id]
FOR XML PATH('')), 1, 2, '') AS [Pack(s) Assigned]
FROM [dbo].[tbl_visit] A
GROUP BY A.[id]) pl
ON pl.visit_id = F.visitid
--Ordering
ORDER BY CAST(F.[Visit Date] AS DATE) asc, F.[Call Date] asc
) rawquery
--where
To get your output in a specific order you need to add an order by after your "rawquery" alias. As it sits right now your query has no order by so you have no way of knowing what order the results will be.
SELECT DISTINCT site_id
, site_number
, [Country Name]
, [Investigator Name]
, [Patient Number]
, [Year of Birth]
, [Visit]
, [Visit Date]
, [Kit Assigned]
, [Confirmation (doc)]
FROM (SELECT TOP 99999999999 B.[id] [site_id]
, B.[site_number] [site_number]
, A.[name] [Country Name]
, B.[site_number] [Site Number]
, B.[site_number] [SiteNumber]
, D.[investigator_name] [Investigator Name]
, C.[spid] [Patient Number]
, E.[YOB] [Year of Birth]
, F.[Visit] [Visit]
, CONVERT(NVARCHAR, F.[Visit Date], 120) [Visit Date]
, Isnull(pl.[Pack(s) Assigned], 'N/A') [Kit Assigned]
, H.[Confirmation (doc)]
FROM (SELECT [id]
, [name]
, [code] [country_code]
FROM [dbo].[tbl_country]) A
INNER JOIN [dbo].[tbl_site] B
ON A.[id] = B.[country_id]
INNER JOIN [dbo].[tbl_subject] C
ON B.[id] = C.[site_id]
LEFT JOIN (SELECT A.id
, A.inv_first_name + ' ' + A.inv_last_name [investigator_name]
FROM vw_site A) D
ON B.[id] = D.[id]
INNER JOIN (SELECT A.[subject_id]
, B.int_value [YOB]
FROM vw_subject_info A
INNER JOIN tbl_custom_data B
ON B.row_id = A.subject_id
AND B.table_name = 'Subject'
AND B.[field_name] = 'Initial_DOB') E
ON C.[id] = E.[subject_id]
INNER JOIN (SELECT subject_id
, VisitID
, VisitScheduleID
, site_id
, site_number
, visit [Visit]
, visit_date_local [Visit Date]
, call_date [Call Date]
FROM vw_visit) F
ON C.[id] = F.[subject_id]
LEFT JOIN (SELECT [visit_id]
, [int_value] [Confirmation (doc)]
FROM [vw_visitDetail]
WHERE [field_name] = 'docId') H
ON F.[VisitID] = H.[visit_id]
--Selecting the packs dispensed at latest dispensing visit
LEFT JOIN (SELECT A.[id] [visit_id]
, Stuff((SELECT ', '
+ Cast(C.[client_pack_number] AS NVARCHAR(MAX))
FROM [dbo].[tbl_visit_pack] B
INNER JOIN [dbo].[tbl_pack] C
ON B.[pack_id] = C.[id]
INNER JOIN dbo.tbl_pack_type pt
ON pt.id = c.pack_type_id
WHERE A.[id] = B.[visit_id]
FOR XML PATH('')), 1, 2, '') AS [Pack(s) Assigned]
FROM [dbo].[tbl_visit] A
GROUP BY A.[id]) pl
ON pl.visit_id = F.visitid --Ordering
ORDER BY Cast(F.[Visit Date] AS DATE) ASC
, F.[Call Date] ASC
) rawquery
--where
Order By YourColumnHere

Updating a table in sql database

I have the following requirement/business rule:
Galaxys
delete * from Galaxys
'append from ADE data - qryGetGalaModel
INSERT INTO tbl Galaxys ( [ID Number], [ID Status], [ Type], [ID Completed], [MK Link ID], [MODEL Link ID], [ID Main Vendor] )
SELECT Ceekay_ID_WO.TNE_NO, Ceekay _TNE_WO.STATUS, Ceekay_TNE_WO.TYPE, Ceekay _TNE_WO.TNE_ID_COMPLETED, Ceekay_TNE_WO.CS_LINK_ID, CStr([cs_link_id]) AS [User Link ID], Ceekay_TNE_WO.SUPPLIER
FROM Ceekay _TNE_WO
WHERE (((Ceekay _TNE_WO.STATUS)<>"CANC") AND ((Ceekay_TNE_WO.WORK_TYPE)="De-Install" Or (Ceekay_TNE_WO.WORK_TYPE)="MBNL-De-Install") AND ((Ceekay_TNE_WO.TNE_COMPLETED) Is Null Or (Ceekay_TNE_WO.TNE_COMPLETED)>=#7/1/2007#) AND ((Ceekay_TNE_WO.TNE_TYPE)="RADIO"))
ORDER BY Ceekay _TNE_WO.TNE_COMPLETED;
'add link ends - qryUpdateAandBends
UPDATE ((((tblGalaxys INNER JOIN SPECTRUM_IQLINK ON tblGalaxys.[User Link ID] = Ceekay _IQLINK.LINK_ID) INNER JOIN Ceekay _LINK_END ON Ceekay_IQLINK.LINK_ID = Ceekay _LINK_END.LINK_ID) INNER JOIN Ceekay_LINK_END AS Ceekay _LINK_END_1 ON Ceekay _IQLINK.LINK_ID = Ceekay_LINK_END_1.LINK_ID) INNER JOIN (qryConvertSiteID AS qryConvertSiteID_1 INNER JOIN tbl CeekayLiteSiteDetails AS tbl CeekayLiteSiteDetails_1 ON qryConvertSiteID_1.Site_ID = tblCeekayLiteSiteDetails_1.Site_ID) ON Ceekay_LINK_END_1.SITE_ID = qryConvertSiteID_1.[site ID]) INNER JOIN (qryConvertSiteID INNER JOIN tblCeekayLiteSiteDetails ON qryConvertSiteID.Site_ID = tblCeekayLiteSiteDetails.Site_ID) ON SPECTRUM_LINK_END.SITE_ID = qryConvertSiteID.[site ID] SET tblGalaxys.[A Cell ID] = [tblCeekayLiteSiteDetails].[cell_id], tblGalaxys.[A Site ID] = [Ceekay_link_end].[site_id], tblGalaxys.[B Cell ID] = [tblCeekayLiteSiteDetails_1].[cell_id], tblGalaxys.[B Site ID] = [spectrum_link_end_1].[site_id]
WHERE (((Ceekay_LINK_END.END_ID)="A") AND ((Ceekay_LINK_END_1.END_ID)="B"));
'add site info - qryUpdateGalaxyDetails
UPDATE (((tblGalaxys INNER JOIN Ceekay_SITE ON tblGalaxys.[A Site ID] = Ceekay_SITE.SITE_ID) LEFT JOIN Ceekay_SITE AS Ceekay_SITE_1 ON tblGalaxys.[B Site ID] = Ceekay_SITE_1.SITE_ID) LEFT JOIN WurzelSitesProgUpdate ON tblGalaxys.[A Site ID] = WurzelSitesProgUpdate.[TM Site ID]) LEFT JOIN WurzelSitesProgUpdate AS WurzelSitesProgUpdate_1 ON tblGalaxys.[B Site ID] = WurzelSitesProgUpdate_1.[TM Site ID] SET tblGalaxys.[A Site Name] = [Ceekay_site].[site_name], tblGalaxys.A Site Region] = IIf([Ceekay_site].[region]=1,"South",IIf([Ceekay_site].[region]=2,"Midlands",IIf([Ceekay_site].[region]=3 Or [Ceekay_site].[region]=4,"North"))), tblGalaxys.[A Site Area] = [WurzelSitesProgUpdate].[area], tblGalaxys.[A Site Programme] = [WurzelSitesProgUpdate].[technology type], tblGalaxys.[B Site Name] = [Ceekay_site_1].[site_name], tblGalaxys.[B Site Region] = IIf([Ceekay_site_1].[region]=1,"South",IIf([Ceekay_site_1].[region]=2,"Midlands",IIf([Ceekay_site_1].[region]=3 Or [Ceekay_site_1].[region]=4,"North"))), tblGalaxys.[B Site Area] = [WurzelSitesProgUpdate_1].[area], tblGalaxys.[B Site Programme] = [WurzelSitesProgUpdate_1].[technology type];
update ML Number qryMakeTempMLNumber
SELECT tblRadioDeinstalls.[TNE Number], SPECTRUM_LNK.ML_NUMBER, SPECTRUM_LNK.LINK_STATUS
INTO tempMLNumber
FROM ((SPECTRUM_LNK INNER JOIN SPECTRUM_NODE ON SPECTRUM_LNK.A_END_NODE_ID = SPECTRUM_NODE.NODE_ID)
INNER JOIN SPECTRUM_NODE AS SPECTRUM_NODE_1 ON SPECTRUM_LNK.B_END_NODE_ID = SPECTRUM_NODE_1.NODE_ID)
INNER JOIN tblRadioDeinstalls ON (tblRadioDeinstalls.[A Site ID] = SPECTRUM_NODE.SITE_ID) AND (SPECTRUM_NODE_1.SITE_ID = tblRadioDeinstalls.[B Site ID])
WHERE (((SPECTRUM_LNK.LINK_TYPE)="R"));
qryUpdateMLNumber
UPDATE tblRadioDeinstalls INNER JOIN tempMLNumber ON tblRadioDeinstalls.[TNE Number] =
tempMLNumber.[TNE Number] SET tblRadioDeinstalls.[ML number] = [ML_NUMBER],
tblRadioDeinstalls.[Link Status] = [LINK_STATUS];
update ML Number qryMakeTempMLNumber
SELECT Galaxys.[TNE Number], Ceekay_LNK.ML_NUMBER, Ceekay _LNK.LINK_STATUS
INTO tempMLNumber
FROM ((Ceekay _LNK INNER JOIN Ceekay _NODE ON Ceekay _LNK.A_END_NODE_ID = Ceekay _NODE.NODE_ID)
INNER JOIN Ceekay _NODE AS Ceekay _NODE_1 ON Ceekay _LNK.B_END_NODE_ID = Ceekay _NODE_1.NODE_ID)
INNER JOIN tblGalaxys ON (tblGalaxys.[A Site ID] = Ceekay_NODE.SITE_ID) AND (Ceekay _NODE_1.SITE_ID = tblGalaxys.[B Site ID])
WHERE (((Ceekay_LNK.LINK_TYPE)="R"));
qryUpdateMLNumber
UPDATE tblGalaxys INNER JOIN tempMLNumber ON tblGalaxys.[TNE Number] =
tempMLNumber.[TNE Number] SET tblGalaxys.[ML number] = [ML_NUMBER],
tblGalaxys.[Link Status] = [LINK_STATUS];
The request is to populate the above in sql database using sql query langauage.
Can someone help please
It looks like you have all the pieces there. Try the update like this:
UPDATE tblRadioDeinstalls
SET tblRadioDeinstalls.[ML number] = [ML_NUMBER],
tblRadioDeinstalls.[Link Status] = [LINK_STATUS]
FROM tblRadioDeinstalls
INNER JOIN tempMLNumber ON tblRadioDeinstalls.[TNE Number] =
tempMLNumber.[TNE Number] ;
Here is a link to documentation and examples for SQL Server Updates http://msdn.microsoft.com/en-us/library/8hwekas8(v=vs.80).aspx
You can use aliases in update statements, this makes it easier to read. Look at the test code below.
DECLARE #tableA TABLE
(
id INT
,MyData VARCHAR(20)
);
INSERT INTO #tableA VALUES (0,'First Element'), (1,'Second Element'), (2, 'Fourth Element')
SELECT * FROM #tableA
UPDATE A
SET a.MyData = 'Third Element'
FROM #tableA AS A
WHERE a.id = 2;
SELECT * FROM #tableA
As you notice instead of UPDATE #tableA AS A I just did UPDATE A and defined A in FROM clause. In UPDATE statement SET always follows UPDATE than the rest of information.

SQL Pivot dynamic query error

I tried to convert rows values into columns...Below is my query...
Select * from (SELECT *
FROM ( SELECT PROJ.PROJ_ID,
PROJ.PROJ_NM AS [Project Name],
PROJ.PROJ_DS AS [Project Description],
convert(varchar(10), PROJ.PROJ_ACTL_LNCH_DT, 110) [Actual Completed Date],
PROJ.PROJ_SMRY_DS AS [Project Summary],
dbo.udf_BankContacts(PROJ.PROJ_ID) AS [BankContact],
convert(varchar(10), PROJ.PROJ_EST_LNCH_DT, 110) AS [Estimated Launch Date],
PROJ.ENTER_DT AS [Begin Date],
PROJ_STA.PROJ_STA_DS AS [Project Status],
SFTW_DEV_MTHD.SFTW_DEV_MTHD_NM AS [Software Development Method],
PROJ_PHASE.PROJ_PHASE_DS AS [Phase],
PROJ_CTGY.PROJ_CTGY_DS AS [Project Category],
(CASE WHEN PROJ.ARCH_IN='0' THEN 'N' ELSE 'C' END) AS [Archive],
PROJ.PHASE_CMNT_TX AS [Phase Comment],
PROD_TYPE_DS
FROM dbo.Project PROJ
left join dbo.PROJ_PROD PP on PROJ.PROJ_ID = PP.PROJ_ID
left join dbo.PROD_TYPE PT on PP.PROD_TYPE_ID = PT.PROD_TYPE_ID
LEFT JOIN DBO.PROJ_STA ON PROJ.PROJ_STA_ID = PROJ_STA.PROJ_STA_ID
left join dbo.SFTW_DEV_MTHD on PROJ.SFTW_DEV_MTHD_ID = SFTW_DEV_MTHD.SFTW_DEV_MTHD_ID
left join dbo.PROJ_PHASE on PROJ.PROJ_PHASE_ID = PROJ_PHASE.PROJ_PHASE_ID
left join dbo.PROJ_CTGY on PROJ.PROJ_CTGY_ID = PROJ_CTGY.PROJ_CTGY_ID
) data
PIVOT
( MAX(PROD_TYPE_DS)
FOR PROD_TYPE_DS IN ([PT1],[PT2])
) pvt2
where PROJ_ID is not null) AS ProdType
LEFT JOIN (SELECT *
FROM
(
select PROJ_ID,
PROJ_APRV_TYPE_DS = case
when col ='PROJ_APRV_TYPE_DS'
then PROJ_APRV_TYPE_DS
else PROJ_APRV_TYPE_DS+col end,
value
from
(
SELECT PROJ.PROJ_ID,
PAT.PROJ_APRV_TYPE_DS PROJ_APRV_TYPE_DS,
convert(varchar(10), PATS.APRV_EXPT_BY_DT, 120) APRV_EXPT_BY_DT,
convert(varchar(10), PATS.APRV_CMPL_DT, 120) APRV_CMPL_DT
FROM dbo.Project PROJ
left join [dbo].[PROJ_APRV_TYPE_STA] PATS
on PROJ.PROJ_ID = PATS.PROJ_ID
left join [dbo].[PROJ_APRV_STA] PAS
on PATS.PROJ_APRV_STA_ID = PAS.PROJ_APRV_STA_ID
right outer join dbo.PROJ_APRV_TYPE PAT
on PATS.PROJ_APRV_TYPE_ID = PAT.PROJ_APRV_TYPE_ID
) s
cross apply
(
select 'PROJ_APRV_TYPE_DS', PROJ_APRV_TYPE_DS union all
select ' Expected Date', APRV_EXPT_BY_DT union all
select ' Completed Date', APRV_CMPL_DT
) c (col, value)
) data
PIVOT
(
MAX(value)
FOR PROJ_APRV_TYPE_DS IN ([RMC Approval],[RMC Approval Expected Date],[RMC Approval Completed Date],[BOD Approval],[BOD Approval Expected Date],[BOD Approval Completed Date])
) pvt1 where PROJ_ID is not null ) AS Approval ON ProdType.PROJ_ID = Approval.PROJ_ID
LEFT JOIN (SELECT *
FROM ( SELECT PROJ.PROJ_ID,
ORG_SHRT_NM
FROM dbo.Project PROJ
left join dbo.PROJ_LGL_ENT_IMPCT PLEI on PROJ.PROJ_ID = PLEI.PROJ_ID
right outer join dbo.LGL_ENT LE on PLEI.LGL_ENT_ID = LE.LGL_ENT_ID
) data
PIVOT
( MAX(ORG_SHRT_NM)
FOR ORG_SHRT_NM IN ([AECB],[FSB],[TRS])
) pvt3
where PROJ_ID is not null) AS LegalEntity ON ProdType.PROJ_ID = LegalEntity.PROJ_ID LEFT JOIN
(;with cte as
(
SELECT PCGU.PROJ_ID,
name = u.USER_LST_NM + ', '+ u.USER_FIRST_NM,
CTC_GRP_DS
FROM dbo.[user] u
left join dbo.PROJ_CTC_GRP_USER PCGU
on u.USER_ID = PCGU.USER_ID
left join dbo.CTC_GRP CG
on PCGU.CTC_GRP_ID = CG.CTC_GRP_ID
)
select *
from
(
select c1.proj_id,
c1.CTC_GRP_DS,
STUFF(
(SELECT ', ' + c2.name
FROM cte c2
where c1.proj_id = c2.proj_id
and c1.CTC_GRP_DS = c2.CTC_GRP_DS
FOR XML PATH (''))
, 1, 1, '') AS name
from cte c1
) d
pivot
(
max(name)
for CTC_GRP_DS in ([Bank Contact],[Dept2])
) piv
where PROJ_ID is not null)
AS Dept ON ProdType.PROJ_ID = Dept.PROJ_ID
I am getting error
Msg 102, Level 15, State 1, Line 84
Incorrect syntax near ';'.
Msg 102, Level 15, State 1, Line 115
Incorrect syntax near ')'.
I am totally confused what i am missing it. I recently started pivot & dynamic query concepts...Please guide on it...
Your error is here.
(;with cte as
(
SELECT PCGU.PROJ_ID,
name = u.USER_LST_NM + ', '+ u.USER_FIRST_NM,
CTC_GRP_DS
FROM dbo.[user] u
left join dbo.PROJ_CTC_GRP_USER PCGU
on u.USER_ID = PCGU.USER_ID
left join dbo.CTC_GRP CG
on PCGU.CTC_GRP_ID = CG.CTC_GRP_ID
)
select *
from
(
select c1.proj_id,
c1.CTC_GRP_DS,
STUFF(
(SELECT ', ' + c2.name
FROM cte c2
where c1.proj_id = c2.proj_id
and c1.CTC_GRP_DS = c2.CTC_GRP_DS
FOR XML PATH (''))
, 1, 1, '') AS name
from cte c1
) d
You cannot have a CTE in sub selects like that.
You could try to put the CTE at the very top, or create a temp table for the select.
The error is with your CTE. You can't stick a CTE inside a query like that
(;with cte as

Resources