Related
Please help, I have a problematic query to display the column OrderNo2.
the following is the query:
SELECT
V.id, V.TypeApv, V.CreateDate,
P.Requestor, VE.VendorName, V.InvoiceNo, V.Hawb,
PA.PaymentFor, V.Amount, V.Curr, V.DueDate, V.Remarks, V.OrderNo,
(SELECT
STUFF((SELECT DISTINCT ', ' + CASE WHEN [e-SAM Case]='Subsequent' OR [e-SAM Case]='DDT' AND [Local SAP PO] LIKE '5%' OR [e-SAM Case]='FBS 4'
THEN PoNo ELSE [Local SAP PO] END
FROM v_copo VC
WHERE VC.AWB1 = V.Hawb
FOR XML PATH('')), 1, 1, '')) AS OrderNo2,
(SELECT ISNULL(OrderNo2, V.OrderNo)) AS OrderNoFinal
FROM
APV_AF V
LEFT JOIN
APV_Person P ON P.id = V.Requestor
LEFT JOIN
APV_Vendor VE ON VE.IDVendor = V.VendorName
LEFT JOIN
APV_Payment PA ON PA.IDPayment = V.PaymentFor
ORDER BY
V.CreateDate DESC
You cannot reference an alias in the same scope where it was defined (apart from the order by clause). Typical work arounds include a subquery or CTE.
In SQL Server though, a simple option is a lateral join:
SELECT
V.id, V.TypeApv, V.CreateDate,
P.Requestor, VE.VendorName, V.InvoiceNo, V.Hawb,
PA.PaymentFor, V.Amount, V.Curr, V.DueDate, V.Remarks, V.OrderNo,
X.OrderNo2,
ISNULL(X.OrderNo2, V.OrderNo) AS OrderNoFinal
FROM APV_AF V
LEFT JOIN APV_Person P ON P.id = V.Requestor
LEFT JOIN APV_Vendor VE ON VE.IDVendor = V.VendorName
LEFT JOIN APV_Payment PA ON PA.IDPayment = V.PaymentFor
OUTER APPLY (
SELECT
STUFF((SELECT DISTINCT ', ' + CASE WHEN [e-SAM Case]='Subsequent' OR [e-SAM Case]='DDT' AND [Local SAP PO] LIKE '5%' OR [e-SAM Case]='FBS 4'
THEN PoNo ELSE [Local SAP PO] END
FROM v_copo VC
WHERE VC.AWB1 = V.Hawb
FOR XML PATH('')), 1, 1, '') AS OrderNo2
) X
ORDER BY V.CreateDate DESC
I have the following complex query which builds a list of columns dynamically before passing them to a second query (with a pivot) and executing it.
I have produced a report in Visual Studio that passes a parameter (#Event) for the user to select an event they want a report to run on. In order for the #Event to be in scope with the #SQL statement it is concatenated as
'+ #Event +'
however when I then run the statement I get a conversion failed error
Conversion failed when converting the varchar value
if I hardcode the values for #Event the query runs correctly.
What have I done wrong that wont let this run?
thanks
DECLARE #sql AS varchar(max)
DECLARE #pivot_list AS varchar(max)
DECLARE #select_list AS varchar(max)
SELECT #pivot_list = COALESCE(#pivot_list + ', ', '') + '[' + CONVERT(varchar, PIVOT_CODE) + ']'
,#select_list = COALESCE(#select_list + ', ', '') + '[' + CONVERT(varchar, PIVOT_CODE) + '] AS [' + CONVERT(varchar, PIVOT_NAME) + ']'
FROM (
SELECT DISTINCT PIVOT_CODE, PIVOT_NAME
FROM (
SELECT s.SESSION_REF AS PIVOT_CODE, s.name as PIVOT_NAME
FROM DELEGATE as d
INNER JOIN DELEGATE_SESSION as ds on d.DELEGATE_REF=ds.DELEGATE_REF
INNER JOIN SESSION as s on ds.SESSION_REF=s.SESSION_REF
where ds.NO_DELEGATES=1 and d.EVENT_REF=#Event
) as rows
) AS PIVOT_CODES
SET #sql = '
;WITH p AS (
select d.DELEGATE_REF as REF, s.SESSION_REF AS PIVOT_CODE, d.name, ds.NO_DELEGATES
, o.COMPANY_NAME as ''Org'', l7.LOOKUP_FULL_DESC as ''Org_Member'', l8.LOOKUP_FULL_DESC as ''Org_Type''
, e.NAME as ''Event'', CAST(d.code AS INTEGER) as Delegate_No, d.member_ref as ''Record_No''
, i.SURNAME, i.FORENAMES, l6.LOOKUP_FULL_DESC as ''Status'', l4.LOOKUP_FULL_DESC as ''Membership'', i_fee.LABEL_NAME as ''Feepayer''
, CAST(d.COMMENT AS NVARCHAR(100)) as ''Comments'', l1.LOOKUP_FULL_DESC as ''Delegate_Type''
, e1.EMAIL_ADDRESS as ''Email''
--, CASE WHEN e1.type = 1236 then e1.EMAIL_ADDRESS WHEN e2.type = 1240 then e2.EMAIL_ADDRESS WHEN e3.type = 1197 then e3.EMAIL_ADDRESS ELSE NULL END as ''Email''
, d.mailing_different, l.ADDRESS1 as ''Mail1'', l.ADDRESS2 as ''Mail2'', l.ADDRESS3 as ''Mail3'', l.TOWN as ''Mail4'', l.POSTCODE as ''Mail5'', l.COUNTRY as ''Mail6''
, d.invoice_different, l2.ADDRESS1 as ''Inv1'', l2.ADDRESS2 as ''Inv2'', l2.ADDRESS3 as ''Inv3'', l2.TOWN as ''Inv4'', l2.POSTCODE as ''Inv5'', l2.COUNTRY as ''Inv6''
, d.TOTAL_AMOUNT, l5.LOOKUP_FULL_DESC as ''Pay''
, CAST(dq1.comments AS NVARCHAR(100)) as ''Q_B_Name'', CAST(dq2.comments AS NVARCHAR(100)) as ''Q_B_Inst'', a.DESCRIPTION as ''Q_Food'', CAST(dq3.comments AS NVARCHAR(100)) as ''Q_Food_Comment'', a2.DESCRIPTION as ''Q_Special'', CAST(dq4.comments AS NVARCHAR(100)) as ''Q_Special_Comment'', CAST(dq5.comments AS NVARCHAR(100)) as ''Q_Twitter'', CAST(dq6.comments AS NVARCHAR(100)) as ''Q_Number'', CAST(dq7.comments AS NVARCHAR(100)) as ''Q_School''
, l3.LOOKUP_FULL_DESC as ''Delegate_Status'', ev.DESCRIPTION as ''Session_Rate'', ev2.DESCRIPTION as ''Rate''
FROM DELEGATE as d
INNER JOIN EVENT as e on d.EVENT_REF=e.EVENT_REF
INNER JOIN DELEGATE_SESSION as ds on d.DELEGATE_REF=ds.DELEGATE_REF
INNER JOIN EVENT_RATE as ev on ds.EVENT_RATE_REF=ev.EVENT_RATE_REF
INNER JOIN SESSION as s on ds.SESSION_REF=s.SESSION_REF
INNER JOIN DELEGATE_SESSION as ds2 on d.DELEGATE_REF=ds2.DELEGATE_REF
INNER JOIN EVENT_RATE as ev2 on ds2.EVENT_RATE_REF=ev2.EVENT_RATE_REF
INNER JOIN EVENT as event2 on ev2.EVENT_REF=event2.EVENT_REF
LEFT JOIN LOCATION as l on d.MAILING_LOCATION=l.LOCATION_REF
LEFT JOIN LOCATION as l2 on d.INVOICE_LOCATION=l2.LOCATION_REF
INNER JOIN MEMBER as m on d.MEMBER_REF=m.MEMBER_REF
LEFT JOIN INDIVIDUAL as i on m.INDIVIDUAL_REF=i.INDIVIDUAL_REF
LEFT JOIN CONTACT as c on i.INDIVIDUAL_REF=c.INDIVIDUAL_REF and c.MAIN_ORGANISATION=''Y''
LEFT JOIN ORGANISATION as o on c.ORGANISATION_REF=o.ORGANISATION_REF and c.MAIN_ORGANISATION=''Y''
LEFT JOIN MEMBER as m2 on o.ORGANISATION_REF=m2.ORGANISATION_REF
LEFT JOIN LOOKUP as l7 on m2.MEMBER_STATUS=l7.LOOKUP_REF
LEFT JOIN ATTRIBUTE as at3 on o.ORGANISATION_REF=at3.ORGANISATION_REF and at3.CODE_TYPE=206 --School type
LEFT JOIN LOOKUP as l8 on at3.ATTR_CODE_REF=l8.LOOKUP_REF
LEFT JOIN LOOKUP as l1 on d.TYPE=l1.LOOKUP_REF
LEFT JOIN LOOKUP as l3 on d.STATUS=l3.LOOKUP_REF
LEFT JOIN LOOKUP as l6 on m.MEMBER_STATUS=l6.LOOKUP_REF
LEFT JOIN LOOKUP as l4 on m.MEMBER_CLASS=l4.LOOKUP_REF
LEFT JOIN LOOKUP as l5 on d.PAY_METHOD=l5.LOOKUP_REF
LEFT JOIN INDIVIDUAL as i_fee on d.FEEPAYING_MEMBER=i_fee.INDIVIDUAL_REF
--LEFT JOIN EMAIL as e1 on d.INDIVIDUAL_REF=e1.INDIVIDUAL_REF and (e1.MAIN_EMAIL=''Y'' and (e1.type=1236))
--LEFT JOIN EMAIL as e2 on d.INDIVIDUAL_REF=e2.INDIVIDUAL_REF and (e2.MAIN_EMAIL=''Y'' and (e2.type=1240))
--LEFT JOIN EMAIL as e3 on d.INDIVIDUAL_REF=e3.INDIVIDUAL_REF and (e3.MAIN_EMAIL=''Y'' and (e3.type=1197))
--LEFT JOIN EMAIL as e4 on d.INDIVIDUAL_REF=e3.INDIVIDUAL_REF and (e3.MAIN_EMAIL=''Y'' and (e3.type=2976))
LEFT JOIN EMAIL as e1 on i.INDIVIDUAL_REF=e1.INDIVIDUAL_REF and e1.MAIN_EMAIL=''Y'' and (e1.type NOT IN (2232,1241,1242,1106,3220,2612))
LEFT JOIN DELEGATE_QUESTION as dq1 on d.DELEGATE_REF=dq1.DELEGATE_REF and dq1.question=2054
LEFT JOIN DELEGATE_QUESTION as dq2 on d.DELEGATE_REF=dq2.DELEGATE_REF and dq2.question=2055
LEFT JOIN DELEGATE_QUESTION as dq3 on d.DELEGATE_REF=dq3.DELEGATE_REF and dq3.question=1620
LEFT JOIN DELEGATE_QUESTION as dq4 on d.DELEGATE_REF=dq4.DELEGATE_REF and dq4.question=1621
LEFT JOIN DELEGATE_QUESTION as dq5 on d.DELEGATE_REF=dq5.DELEGATE_REF and dq5.question=2626
LEFT JOIN DELEGATE_QUESTION as dq6 on d.DELEGATE_REF=dq6.DELEGATE_REF and dq6.question=3155
LEFT JOIN DELEGATE_QUESTION as dq7 on d.DELEGATE_REF=dq7.DELEGATE_REF and dq7.question=2979
LEFT JOIN ANSWER as a on dq3.ANSWER_REF=a.ANSWER_REF
LEFT JOIN ANSWER as a2 on dq4.ANSWER_REF=a2.ANSWER_REF
where ds.NO_DELEGATES=1 and d.EVENT_REF='+ #Event +'
)
SELECT event, delegate_no, record_no, Org, Org_Member, Org_Type, name, surname,forenames,status,membership,feepayer
, comments, Delegate_Type
, Email
, mailing_different, Mail1, Mail2, Mail3, Mail4, Mail5, Mail6, invoice_different, Inv1, Inv2, Inv3, Inv4, Inv5, Inv6
, total_amount, pay
, Q_B_Name, Q_B_Inst, Q_Food, Q_Food_Comment, Q_Special, Q_Special_Comment, Q_Twitter, Q_Number, Q_School, Delegate_Status, Rate
, ' + #select_list + '
FROM p
PIVOT (
MAX(Session_Rate)
FOR PIVOT_CODE IN (
' + #pivot_list + '
)
) AS pvt
'
EXEC (#sql)
Don't concatenate your values, use parametrised SQL. Concatenating like that is bad, as it leaves you open to injection.
Change your WHERE clause to d.EVENT_REF= #dEvent and then change your EXEC to:
EXEC sp_executesql #SQL, N'#dEvent int', #dEvent = #Event;
Note, I have guess yoru datatype, as I can't see a DECLARE in your provided SQL.
Also, instead of using code like '[' + CONVERT(varchar, PIVOT_CODE) + ']' use QUOTENAME(PIVOT_CODE). That'll cope with what ever value is passed far better than the former. For example, if someone (silly enough) ever creates an object with a ] in the name, then '[' + CONVERT(varchar, PIVOT_CODE) + ']' would fail.
Helpful tip: When writing Dyanmic SQL, format it as well. it'll make things far easier to debug. Just because your SQL is dynamic doesn't mean you should forget simple things like good use of whitespace and linebreaks.
I work with the AventureWorks2014 database in Microsoft SQL Server. I need to create a view that will show the CustomerID, the full name and the TOTAL amount sold to client through the web.
My problem is that I can't seem to get the values corresponding to a single customer add up so that a single customer answers to a single line in my result. This is the code I have, any help would be appreciated. I basically need to show the total amount sold to clients on the web.
if object_id('vTotalWebSalesPerCustomer', 'v') is not null
drop view vTotalWebSalesPerCustomer;
go
create view vTotalWebSalesPerCustomer
as
select distinct
c.CustomerID,
ltrim(rtrim(concat(concat(concat(concat(concat(concat(concat(p.Title, ' '), p.LastName), ', '), ' '), p.FirstName), ' '), p.Suffix))) as NomClient,
soh.TotalDue
from
[Sales].[Customer] as c
left join
[Person].[Person] as p on c.CustomerID = p.BusinessEntityID
left join
[Sales].[SalesOrderHeader] as soh on soh.CustomerID = c.CustomerID
where
year(soh.OrderDate) = 2014
and datepart(quarter, soh.OrderDate) = 1
and [OnlineOrderFlag] = 1
go
select *
from vTotalWebSalesPerCustomer
Thanks
Sounds like you need to use GROUP BY and SUM(), example:
SELECT column-names
FROM table-name
WHERE condition
GROUP BY column-names
ORDER BY column-names
Such as:
SELECT SUM(O.TotalPrice), C.FirstName, C.LastName
FROM [Order] O JOIN Customer C
ON O.CustomerId = C.Id
GROUP BY C.FirstName, C.LastName
ORDER BY SUM(O.TotalPrice) DESC
Would return:
Sum FirstName LastName
117483.39 Horst Kloss
115673.39 Jose Pavarotti
113236.68 Roland Mendel
57317.39 Patricia McKenna
52245.90 Paula Wilson
34101.15 Mario Pontes
32555.55 Maria Larsson
DISTINCT filters result rows to remove duplicates. What I think you want is to aggregate rows. Perhaps this will do what you want:
create view vTotalWebSalesPerCustomer as
select c.CustomerID,
ltrim(rtrim(concat(concat(concat(concat(concat(concat(concat(p.Title, ' '), p.LastName), ', '), ' '), p.FirstName), ' '), p.Suffix))) as NomClient,
sum(soh.TotalDue) as TotalDue
from [Sales].[Customer] as c
left join [Person].[Person] as p on c.CustomerID = p.BusinessEntityID
left join [Sales].[SalesOrderHeader] as soh on soh.CustomerID = c.CustomerID
where year(soh.OrderDate) = 2014 and datepart(quarter, soh.OrderDate)=1 and [OnlineOrderFlag] = 1
group by c.CustomerID,NomClient
Note that I removed distinct, added sum operator on the amount you want to total, and group by the customer id and name fields (SQL Server requires that you list in the GROUP BY all result columns which are not being aggregated).
You can use the following VIEW using a GROUP BY on the SELECT:
IF OBJECT_ID('vTotalWebSalesPerCustomer', 'v') IS NOT NULL
DROP VIEW vTotalWebSalesPerCustomer;
GO
CREATE VIEW vTotalWebSalesPerCustomer AS
SELECT
x.CustomerID,
LTRIM(RTRIM(CONCAT(p.Title, ' ', p.LastName, ', ', p.FirstName, ' ', p.Suffix))) AS NomClient,
x.TotalDue
FROM (
SELECT
c.CustomerID AS CustomerID,
SUM(soh.TotalDue) AS TotalDue
FROM [Sales].[Customer] AS c
LEFT JOIN [Sales].[SalesOrderHeader] AS soh ON soh.CustomerID = c.CustomerID
WHERE YEAR(soh.OrderDate) = 2014 AND DATEPART(quarter, soh.OrderDate) = 1 AND [OnlineOrderFlag] = 1
GROUP BY c.CustomerID
)x LEFT JOIN [Person].[Person] AS p ON x.CustomerID = p.BusinessEntityID
GO
Note: You only need one CONCAT function to concat all string values.
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.
I have 3 tables. The query returned the desired result just the sorting of records. I added Order By but it did not work.
Result should be:
I got the result it is just the sorting of records. I want to order by the ID but it is not working.
QUERY:
WITH NAMES AS (
SELECT
P.NAMES,
P.CODE,
Q.NUM_TYP,
Q.PHONE_NUM
FROM
dbo.NAMES P
INNER JOIN dbo.PHONE Q
ON P.ID = Q.ID
LEFT JOIN DBO.ADDRESS S
ON P.PRSN_IK = S.PRSN_IK
WHERE S.ADDR Is Null
)
SELECT *
FROM
NAMES
PIVOT (Max(PHONE_NUM) FOR NUM_TYP IN (WORK, HOME)) R;
Appreciate any input. Thanks.
try trhis :
select f1.Name, nullif(f1.code, '') Code ,
isnull(f2.phone_num, 'N/A') work_phone_num, isnull(f3.phone_num, 'N/A') home_phone_num
from Names f1
left outer join Phone f2 on f1.id=f2.id and f2.Num_type='WORK'
left outer join Adress f2b on f2.id=f2b.id and f2.num_type=f2b.add_type
left outer join Phone f3 on f1.id=f3.id and f3.Num_type='HOME'
left outer join Adress f3b on f3.id=f3b.id and f3.num_type=f3b.add_type
where f2b.id is null or f3b.id is null
given that your query is working, this should work :
;WITH NAMES AS (
SELECT
P.NAMES,
P.CODE,
Q.NUM_TYP,
Q.PHONE_NUM
FROM dbo.NAMES P
INNER JOIN dbo.PHONE Q
ON P.ID = Q.ID
LEFT JOIN DBO.ADDRESS S
ON P.PRSN_IK = S.PRSN_IK
WHERE S.ADDR Is Null
), PIVOTED
AS
(
SELECT *
FROM NAMES
PIVOT (Max(PHONE_NUM) FOR NUM_TYP IN (WORK, HOME)) R
)
SELECT * FROM PIVOTED piv
inner join [dbo].[NAMES] nam
on piv.names = nam.names
ORDER BY nam.ID
I have included P.ID and wrapped everything under subquery.