I have the below query running in SQL Server. In a nutshell, I have 3 somewhat identical queries "unioned". When I start the query, it runs and produces incremental results in the Results pane. But, once it reaches 264,619 records (first 5 minutes), it just stops producing results, yet the query is running and has been running for 30 minutes. Any ideas why this is happening? I understand the query below is kind of long/semi-complex, so my apologies, I couldn't make it any simpler (I'm hoping someone might be able to point me in a direction that I would be able to make the query below a little simpler). Below the query is a screenshot of the results pane. I'm wondering if the query is deadlocked somewhere or running into an infinite loop/etc.:
select
Q1.[Transaction Identifier],
row_number() over (order by (select 1)) as 'Transaction Sequence Number',
Q1.HL_Acct_ID,
Q1.AcctNumber,
Q1.AcctType,
Q1.AcctSource,
Q1.DUNS_NBR,
Q1.DBPLCR_CONTACT_ID,
Q1.CellCode,
Q1.OfferCode,
Q1.ResponseType,
Q1.ResponseDate,
Q1.ResponseQuantity,
Q1.ResponseValue,
Q1.ResponseChannel,
Q1.[Cookie ID],
Q1.[IP Address],
Q1.[Device ID],
Q1.[CUSTOM_TEXT_01],
Q1.[CUSTOM_TEXT_02],
Q1.[CUSTOM_TEXT_03],
Q1.[CUSTOM_TEXT_04],
Q1.[CUSTOM_TEXT_05]
from
(
select
'ACCT PROMORESP' as 'Transaction Identifier',
s.HL_ACCT_ID as 'HL_Acct_ID',
null as [AcctNumber],
null as [AcctType],
null as [AcctSource],
null as [DUNS_NBR],
null as [DBPLCR_CONTACT_ID],
s.CELLCODE as [CellCode],
case
when c.URL is not null then c.URL
else '-1'
end as [OfferCode],
case
when c.EventDate is not null then 'Click'
when c.EventDate is null then
case
when sub.status = 'unsubscribed' then 'Unsubscribe'
when sub.status = 'bounced' then 'Bounce'
when sub.status = 'held' then 'Bounce'
end
end as [ResponseType],
convert(varchar, c.EventDate, 112) as [ResponseDate],
null as [ResponseQuantity],
null as [ResponseValue],
'Email' as [ResponseChannel],
null as [Cookie ID],
null as [IP address],
null as [Device ID],
null as [CUSTOM_TEXT_01],
null as [CUSTOM_TEXT_02],
null as [CUSTOM_TEXT_03],
null as [CUSTOM_TEXT_04],
null as [CUSTOM_TEXT_05]
from C1111111.[151222_Hostess Ensemble] s with (nolock)
inner join C1111111._subscribers sub with (nolock) on sub.SubscriberKey = s.Email
left join C1111111._click c with (nolock) on c.JobID in
(
select j.fkJobId from tblJobs_Lists j with (nolock)
inner join customobject c with (nolock) on j.customobjectid = c.customobjectid
where c.memberid = 1111111
and c.customobjectname like '151222_Hostess Ensemble'
)
and c.SubscriberKey = s.Email
where c.EventDate is not null or (c.EventDate is null and (sub.status in ('unsubscribed','bounced','held'))) and c.isunique = 1
union all
select
'ACCT PROMORESP' as 'Transaction Identifier',
s.HL_ACCT_ID as 'HL_Acct_ID',
null as [AcctNumber],
null as [AcctType],
null as [AcctSource],
null as [DUNS_NBR],
null as [DBPLCR_CONTACT_ID],
s.CELLCODE as [CellCode],
'-1' as [OfferCode],
case
when o.EventDate is not null then 'Message Open'
when o.EventDate is null then
case
when sub.status = 'unsubscribed' then 'Unsubscribe'
when sub.status = 'bounced' then 'Bounce'
when sub.status = 'held' then 'Bounce'
end
end as [ResponseType],
convert(varchar, o.EventDate, 112) as [ResponseDate],
null as [ResponseQuantity],
null as [ResponseValue],
'Email' as [ResponseChannel],
null as [Cookie ID],
null as [IP address],
null as [Device ID],
null as [CUSTOM_TEXT_01],
null as [CUSTOM_TEXT_02],
null as [CUSTOM_TEXT_03],
null as [CUSTOM_TEXT_04],
null as [CUSTOM_TEXT_05]
from C1111111.[151222_Hostess Ensemble] s with (nolock)
inner join C1111111._subscribers sub with (nolock) on sub.SubscriberKey = s.Email
left join C1111111._open o with (nolock) on o.JobID in
(
select j.fkJobId from tblJobs_Lists j with (nolock)
inner join customobject c with (nolock) on j.customobjectid = c.customobjectid
where c.memberid = 1111111
and c.customobjectname like '151222_Hostess Ensemble'
)
and o.SubscriberKey = s.Email
where o.EventDate is not null or (o.EventDate is null and (sub.status in ('unsubscribed','bounced','held'))) and o.isunique = 1
UNION ALL
select
'ACCT PROMORESP' as 'Transaction Identifier',
s.HL_ACCT_ID as 'HL_Acct_ID',
null as [AcctNumber],
null as [AcctType],
null as [AcctSource],
null as [DUNS_NBR],
null as [DBPLCR_CONTACT_ID],
s.CELLCODE as [CellCode],
'-1' as [OfferCode],
null as [ResponseType],
convert(varchar, o.EventDate, 112) as [ResponseDate],
null as [ResponseQuantity],
null as [ResponseValue],
'Email' as [ResponseChannel],
null as [Cookie ID],
null as [IP address],
null as [Device ID],
null as [CUSTOM_TEXT_01],
null as [CUSTOM_TEXT_02],
null as [CUSTOM_TEXT_03],
null as [CUSTOM_TEXT_04],
null as [CUSTOM_TEXT_05]
from C1111111.[151222_Hostess Ensemble] s with (nolock)
inner join C1111111._subscribers sub with (nolock) on sub.SubscriberKey = s.Email
left join C1111111._open o with (nolock) on o.JobID in
(
select j.fkJobId from tblJobs_Lists j with (nolock)
inner join customobject c with (nolock) on j.customobjectid = c.customobjectid
where c.memberid = 1111111
and c.customobjectname like '151222_Hostess Ensemble'
)
left join C1111111._click cl with (nolock) on o.JobID in
(
select j.fkJobId from tblJobs_Lists j with (nolock)
inner join customobject c with (nolock) on j.customobjectid = c.customobjectid
where c.memberid = 1111111
and c.customobjectname like '151222_Hostess Ensemble'
)
and cl.SubscriberKey = s.Email
where cl.EventDate is null and o.EventDate is null and sub.status not in ('unsubscribed','bounced','held')) as Q1
Without the table definitions I can't verify that this is correct, but this would be my take at a simplification of the above, with an assumption about two fixes in the join conditions:
set transaction isolation level read uncommitted;
WITH JobIDs AS
(
select j.fkJobId from tblJobs_Lists j
inner join customobject c on j.customobjectid = c.customobjectid
where c.memberid = 1111111
and c.customobjectname = '151222_Hostess Ensemble'
)
select
'ACCT PROMORESP' as 'Transaction Identifier',
row_number() over (order by (select 1)) as 'Transaction Sequence Number',
s.HL_ACCT_ID as 'HL_Acct_ID',
null as [AcctNumber],
null as [AcctType],
null as [AcctSource],
null as [DUNS_NBR],
null as [DBPLCR_CONTACT_ID],
s.CELLCODE as [CellCode],
X.OfferCode,
X.ResponseType,
convert(varchar, X.EventDate, 112) as [ResponseDate],
null as [ResponseQuantity],
null as [ResponseValue],
'Email' as [ResponseChannel],
null as [Cookie ID],
null as [IP address],
null as [Device ID],
null as [CUSTOM_TEXT_01],
null as [CUSTOM_TEXT_02],
null as [CUSTOM_TEXT_03],
null as [CUSTOM_TEXT_04],
null as [CUSTOM_TEXT_05]
from
(
SELECT
s.HL_ACCT_ID,
s.CELLCODE,
s.Email,
case sub.status
when 'unsubscribed' then 'Unsubscribe'
when 'bounced' then 'Bounce'
when 'held' then 'Bounce'
end as [ResponseType],
sub.status
from C1111111.[151222_Hostess Ensemble] s
inner join C1111111._subscribers sub on sub.SubscriberKey = s.Email
) as s
left join C1111111._open o on o.JobID in (select fkJobId from JobIDs)
-- DON'T YOU NEED A "and o.SubscriberKey = s.Email" HERE?
and o.SubscriberKey = s.Email
left join C1111111._click cl on cl.JobID in (select fkJobId from JobIDs)
-- LOOK ABOVE, was "o.JobID", **REALLY**
and cl.SubscriberKey = s.Email
cross apply (
select
'-1' as [OfferCode],
case
when o.EventDate is not null then 'Message Open'
else s.[ResponseType]
end as [ResponseType],
o.EventDate
where o.EventDate is not null or (o.EventDate is null and (s.status in ('unsubscribed','bounced','held'))) and o.isunique = 1
UNION ALL
select
isnull(cl.URL,'-1') as [OfferCode],
case
when c.EventDate is not null then 'Click'
else s.[ResponseType]
end as [ResponseType],
cl.EventDate
where cl.EventDate is not null or (cl.EventDate is null and (s.status in ('unsubscribed','bounced','held'))) and cl.isunique = 1
union all
select
'-1' as [OfferCode],
NULL AS [ResponseType],
null as EventDate
where cl.EventDate is null and o.EventDate is null and s.status not in ('unsubscribed','bounced','held')
) AS X
Related
I have a view like this in SQL Server:
ALTER VIEW [dbo].[myUsers]
AS
SELECT
T1.*,
STRING_AGG(gr.Name, '; ') WITHIN GROUP (ORDER BY gr.Name) AS MemberOf
FROM
(SELECT
mu.Id,
CASE
WHEN iu.ObjectGuid IS NULL
THEN u.Username
ELSE iu.SAMAccountName
END AS Username,
CASE
WHEN iu.ObjectGuid IS NULL
THEN u.FirstName
ELSE iu.GivenName
END AS FirstName,
CASE
WHEN iu.ObjectGuid IS NULL
THEN u.LastName
ELSE iu.LastName
END AS LastName,
CASE
WHEN iu.ObjectGuid IS NULL
THEN u.Email
ELSE iu.Email
END AS Email,
CASE
WHEN iu.ObjectGuid IS NULL
THEN u.Phone
ELSE iu.Telephone
END AS Phone,
CASE
WHEN iu.ObjectGuid IS NULL
THEN u.Mobile
ELSE iu.Mobile
END AS Mobile,
CASE
WHEN iu.ObjectGuid IS NULL
THEN u.CompanyCode
ELSE co.Code
END AS CompanyCode,
co.Name,
CASE
WHEN iu.ObjectGuid IS NULL
THEN 0
ELSE 1
END AS IsNotMaster
FROM
MasterUsers mu
LEFT JOIN
Users u ON u.Id = mu.UsersId
LEFT JOIN
InternalUsers iu ON iu.ObjectGuid = mu.ObjectsGUID
LEFT JOIN
Companies co ON co.name = iu.company
WHERE
iu.ObjectGuid IS NULL OR iu.ModifiedStatus < 100) AS T1
LEFT JOIN
MasterUsers mu ON mu.Username = T1.Email
LEFT JOIN
UsersGroups ug ON ug.MasterUsersId = mu.Id
LEFT JOIN
Groups gr ON gr.Id = ug.GroupsId
GROUP BY
t1.id, T1.Username, T1.FirstName, T1.LastName, T1.Email,
T1.Phone, T1.Mobile, T1.CompanyCode, T1.Name, T1.IsNotMaster
When I run it and filter by Username and equal, it's pretty fast (a few ms):
SELECT [Id]
,[Username]
,[FirstName]
,[LastName]
,[Email]
,[Phone]
,[Mobile]
,[CompanyCode]
,[Name]
,[IsNotMaster]
,[MemberOf]
FROM [dbo].[myUsers]
WHERE Username = 'testuser'
but if I use contains on Username, it become very slow (such as 3/4 seconds):
SELECT [Id]
,[Username]
,[FirstName]
,[LastName]
,[Email]
,[Phone]
,[Mobile]
,[CompanyCode]
,[Name]
,[IsNotMaster]
,[MemberOf]
FROM [dbo].[myUsers]
WHERE Username LIKE '%testuser%'
Where could I improve the query, in your opinion? Are indexes on the view is possible?
I could change the view itself or add/edit indexes, but not add the filtering (i.e. Username and where) inside it (since I call it wherever, for various purpose, and must be generic).
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 the following query. And need to sum all returned by the query "distinct case" values withing a row populated in another column "TotalDepartmentsCount"
;WITH CTE
AS
(
Select t.ID As [CTE_ID]
,count(distinct case when e.Department='M' then t.ID else null end) as M_Marketing
,count(distinct case when e.Department='S' then t.ID else null end) as S_Sales
,count(distinct case when e.Department='U' then t.ID else null end) as U_Utilization
,count(distinct case when e.Department=' ' then t.ID else null end) as No_NoDepartment
From dbo.Table t (nolock)
Left Join dbo.ClearedEmployee ce (nolock) ON t.ID = ce.building_fk
Join dbo.Employee e (nolock) ON ce.employee_fk = e.employee_pk
Group By t.ID
)
Select *, t.ID
From CTE c (nolock)
FULL JOIN dbo.Table t (nolock) ON t.ID=c.[CTE_ID]
Order By t.ID ASC;
To do it I added this code in the select list:
sum(cast(e.Department as int)) As TotalDepartmentsCount
But this does not sum up correctly (see screenshot below). Please advise.
This is how I want to have my output (see the TotalDepartmentsCount table)
Why not just add the columns together once you've calculated them? e.g.:
;WITH CTE
AS
(
Select t.ID As [CTE_ID]
,count(distinct case when e.Department='M' then t.ID else null end) as M_Marketing
,count(distinct case when e.Department='S' then t.ID else null end) as S_Sales
,count(distinct case when e.Department='U' then t.ID else null end) as U_Utilization
,count(distinct case when e.Department=' ' then t.ID else null end) as No_NoDepartment
From dbo.Table t (nolock)
Left Join dbo.ClearedEmployee ce (nolock) ON t.ID = ce.building_fk
Join dbo.Employee e (nolock) ON ce.employee_fk = e.employee_pk
Group By t.ID
)
Select *
, t.ID
, isnull(M_Marketing, 0) + isnull(S_Sales, 0) + isnull(U_Utilization, 0) + isnull(No_NoDepartment, 0) as TotalDepartments
From CTE c (nolock)
FULL JOIN dbo.Table t (nolock) ON t.ID=c.[CTE_ID]
Order By t.ID ASC;
Your CTE currently computes 4 counts by filtering based on department. What you want is a 5th count that includes all rows (e.g., no filtering). So you should be able to add that column to your CTE like so:
;WITH CTE
AS
(
Select t.ID As [CTE_ID]
,count(distinct case when e.Department='M' then t.ID else null end) as M_Marketing
,count(distinct case when e.Department='S' then t.ID else null end) as S_Sales
,count(distinct case when e.Department='U' then t.ID else null end) as U_Utilization
,count(distinct case when e.Department=' ' then t.ID else null end) as No_NoDepartment
,count(distinct t.ID) as TotalDepartmentsCount
From dbo.Table t (nolock)
Left Join dbo.ClearedEmployee ce (nolock) ON t.ID = ce.building_fk
Join dbo.Employee e (nolock) ON ce.employee_fk = e.employee_pk
Group By t.ID
)
The above will work as long as the Department column only contains the four specific values used in distinct cases ('M', 'S', 'U', and ' '). If you can have other Department values that you need to ignore, you can change the TotalDepartmentsCount column in your CTE to be calculated like this:
,count(distinct case when e.Department in ('M', 'S', 'U', ' ') then t.ID else null end) as TotalDepartmentsCount
Or you can simply compute the sum of the four columns in your final query, like so:
Select c.*
, (M_Marketing + S_Sales + U_Utilization + No_NoDepartment) as TotalDepartmentsCount
, t.ID
From CTE c (nolock)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
So i have an error found in my procedure where my query string part of the OPENQUERY is exceeding the maximum defined limits of 8000 characters. What can I do?
The error
The character string that starts with 'select distinct UPPER (case when cast(i.attendantaddress as varchar(30)) is null then i.specialnotes else cast(i.attendantaddress' is too long. Maximum length is 8000.--
The stored procedure
CREATE procedure [dbo].[proc_GetFreePatients1_20apr]
as
declare #temp table(CONTROLNO varchar(max), UHID varchar(250),PATIENTNAME varchar(250),AGE INT,GENDER VARCHAR(1),ADRESS varchar(500),CONTACTNUMBER varchar(20),IPID varchar(20),BED varchar(20),REASONFORADMISSION varchar(max),DIAGNOSIS varchar(max),ADMITDATETIME datetime,DOCTOR varchar(150),
SPECIALITY varchar(500),REFERREDDOCTOR varchar(500),RECOMMENDEDBY varchar(500),EMERGENCYCOLDCASE varchar(500),WARD varchar(150))
insert #temp
select * from openquery(ahdelwards,'select distinct UPPER (case when cast(i.attendantaddress as varchar(30)) is null then i.specialnotes else cast(i.attendantaddress as varchar(30)) end) CONTROLNO,pm.registrationno,
rp.firstname||'' ''||rp.middlename||'' ''||rp.lastname as Patientname,rp.age,
(case when rp.gender=71 then ''F''
else ''M'' end ) GENDER,
ad.address1||'',''||ad.address2||'',''||c.cityname||'',''||sm.statename ADRESS,
(case when ad.residencenumber is null then
(case when ad.emergencynumber is null then ad.mobilenumber
when ad.emergencynumber is not null then ad.emergencynumber
when ad.mobilenumber is null then ad.emergencynumber
when ad.mobilenumber is not null then ad.mobilenumber end) else ad.residencenumber end) CONTACTNUMBER,
i.inpatientno,
bm.bedcode,
I.REASONFORADMISSION,
(select dt.parametervalue
from wards.dischargesummdtls dt
where dt.parammappingid in
(select pm.parammappingid
from wards.parametermapping pm
where pm.parameterid = 1299)
and dt.status = 1
and dt.dischargeno in
(select dy.dischargeno
from wards.dischargesumm_dync dy
where dy.ipno = i.inpatientno)) diagnosis,
i.dateofadmission,
e.FIRSTNAME||'' ''||e.MIDDLENAME||'' ''||e.LASTNAME as doctor,
f_getspeciality(i.admittingdoctor)Speciality,
f_getemployeename(i.referreddoctor)referreddoctor,
UPPER(i.wardnurse) RECOMMENDEDBY,
UPPER(i.housekeeping) EMERGENCYCOLDCASE,
l.leveldetailname
from billing.pateintpolicydetails pd
left join billing.patientpolicymaster pm
on pd.policymasterid = pm.patientpolicymasterid
and pd.policystatus = 1
and pd.aggrementid = 60429
join adt.inpatientmaster i
on i.uhid = pm.registrationno
join registration.patient rp
on rp.uhid = i.uhid
join
registration.addressmaster ad on rp.registrationid=ad.registrationid and ad.addresstypeid=''2'' and ad.status=''1''
inner join
ehis.countrymaster cm on cm.countrycode=ad.country
inner join
ehis.statemaster sm on sm.statecode=ad.state and sm.status=''1''
inner join
ehis.districtmaster dm on dm.districtcode=ad.district and dm.status=''1'' and dm.stateid=sm.stateid
inner join
ehis.citymaster c on c.citycode=ad.city and c.status=''1'' and c.districtid=dm.districtid
join adt.bedmaster bm
on bm.bedid = i.bedid
join hr.employee_main_details e
on e.employeeid = i.admittingdoctor
join adt.leveldetail l
on l.leveldetailid = bm.leveldetailid
where pm.locationid = 10701
and i.locationid = 10701
and i.status not in (7,11)
union
select distinct UPPER (case when cast(i.attendantaddress as varchar(30)) is null then i.specialnotes else cast(i.attendantaddress as varchar(30)) end) CONTROLNO,pm.registrationno,
rp.firstname||'' ''||rp.middlename||'' ''||rp.lastname as Patientname,rp.age, (case when rp.gender=71 then ''F''
else ''M'' end ) GENDER,
ad.address1||'',''||ad.address2||'',''||c.cityname||'',''||sm.statename ADRESS,
(case when ad.residencenumber is null then
(case when ad.emergencynumber is null then ad.mobilenumber
when ad.emergencynumber is not null then ad.emergencynumber
when ad.mobilenumber is null then ad.emergencynumber
when ad.mobilenumber is not null then ad.mobilenumber end) else ad.residencenumber end) CONTACTNUMBER,i.inpatientno,
bm.bedcode,
I.REASONFORADMISSION,
(select dt.parametervalue
from wards.dischargesummdtls dt
where dt.parammappingid in
(select pm.parammappingid
from wards.parametermapping pm
where pm.parameterid = 1299)
and dt.status = 1
and dt.dischargeno in
(select dy.dischargeno
from wards.dischargesumm_dync dy
where dy.ipno = i.inpatientno)) diagnosis,
i.dateofadmission,
e.FIRSTNAME||'' ''||e.MIDDLENAME||'' ''||e.LASTNAME as doctor,
f_getspeciality(i.admittingdoctor)Speciality,
f_getemployeename(i.referreddoctor)referreddoctor,
UPPER(i.wardnurse) RECOMMENDEDBY,
UPPER(i.housekeeping) EMERGENCYCOLDCASE,
l.leveldetailname
from billing.pateintpolicydetails pd
full outer join billing.patientpolicymaster pm
on pd.policymasterid = pm.patientpolicymasterid
and pd.policystatus = 1
join adt.inpatientmaster i
on i.uhid = pm.registrationno
join registration.patient rp
on rp.uhid = i.uhid
join
registration.addressmaster ad on rp.registrationid=ad.registrationid and ad.addresstypeid=''2'' and ad.status=''1''
inner join
ehis.countrymaster cm on cm.countrycode=ad.country
inner join
ehis.statemaster sm on sm.statecode=ad.state and sm.status=''1''
inner join
ehis.districtmaster dm on dm.districtcode=ad.district and dm.status=''1'' and dm.stateid=sm.stateid
inner join
ehis.citymaster c on c.citycode=ad.city and c.status=''1'' and c.districtid=dm.districtid
join adt.bedmaster bm
on bm.bedid = i.bedid
join hr.employee_main_details e
on e.employeeid = i.admittingdoctor
join adt.leveldetail l
on l.leveldetailid = bm.leveldetailid
and l.leveldetailid not in (221,257)
where i.freepatient = 1
and pm.locationid = 10701
and i.locationid = 10701
and i.status not in (7,11)
union
select distinct UPPER (case when cast(i.attendantaddress as varchar(30)) is null then i.specialnotes else cast(i.attendantaddress as varchar(30)) end) CONTROLNO,pm.registrationno,
rp.firstname||'' ''||rp.middlename||'' ''||rp.lastname as Patientname,rp.age, (case when rp.gender=71 then ''F''
else ''M'' end ) GENDER,
ad.address1||'',''||ad.address2||'',''||c.cityname||'',''||sm.statename ADRESS,
(case when ad.residencenumber is null then
(case when ad.emergencynumber is null then ad.mobilenumber
when ad.emergencynumber is not null then ad.emergencynumber
when ad.mobilenumber is null then ad.emergencynumber
when ad.mobilenumber is not null then ad.mobilenumber end) else ad.residencenumber end) CONTACTNUMBER,
i.inpatientno,
bm.bedcode,
I.REASONFORADMISSION,
(select dt.parametervalue
from wards.dischargesummdtls dt
where dt.parammappingid in
(select pm.parammappingid
from wards.parametermapping pm
where pm.parameterid = 1299)
and dt.status = 1
and dt.dischargeno in
(select dy.dischargeno
from wards.dischargesumm_dync dy
where dy.ipno = i.inpatientno)) diagnosis,
i.dateofadmission,
e.FIRSTNAME||'' ''||e.MIDDLENAME||'' ''||e.LASTNAME as doctor,
f_getspeciality(i.admittingdoctor)Speciality,
f_getemployeename(i.referreddoctor)referreddoctor,
UPPER(i.wardnurse) RECOMMENDEDBY,
UPPER(i.housekeeping) EMERGENCYCOLDCASE,
l.leveldetailname
from billing.pateintpolicydetails pd
full outer join billing.patientpolicymaster pm
on pd.policymasterid = pm.patientpolicymasterid
and pd.policystatus = 1
join adt.inpatientmaster i
on i.uhid = pm.registrationno
join registration.patient rp
on rp.uhid = i.uhid
join
registration.addressmaster ad on rp.registrationid=ad.registrationid and ad.addresstypeid=''2'' and ad.status=''1''
inner join
ehis.countrymaster cm on cm.countrycode=ad.country
inner join
ehis.statemaster sm on sm.statecode=ad.state and sm.status=''1''
inner join
ehis.districtmaster dm on dm.districtcode=ad.district and dm.status=''1'' and dm.stateid=sm.stateid
inner join
ehis.citymaster c on c.citycode=ad.city and c.status=''1'' and c.districtid=dm.districtid
join adt.bedmaster bm
on bm.bedid = i.bedid
join hr.employee_main_details e
on e.employeeid = i.admittingdoctor
join adt.leveldetail l
on l.leveldetailid = bm.leveldetailid
and l.leveldetailid in (221,257)
where i.freepatient = 1
and pm.locationid = 10701
and i.locationid = 10701
and i.status not in (7,11)
')
--pd.aggrementid IN (60429,7140)
select distinct * from #temp order by 11 asc
Declare #strSQL varchar(max)
set #strSQL = N'<your query here>'
exec #strSQL at <YourLinkedServerName>
This bypasses any limitation of the 8000 character limit.
May be something like below:
CREATE PROCEDURE [dbo].[proc_GetFreePatients1_20apr]
AS
BEGIN
DECLARE #temp TABLE(CONTROLNO varchar(max), UHID varchar(250),PATIENTNAME varchar(250),AGE INT,GENDER VARCHAR(1),ADRESS varchar(500),
CONTACTNUMBER varchar(20),IPID varchar(20),BED varchar(20),REASONFORADMISSION varchar(max),DIAGNOSIS varchar(max),
ADMITDATETIME datetime,DOCTOR varchar(150),SPECIALITY varchar(500),REFERREDDOCTOR varchar(500),RECOMMENDEDBY varchar(500),
EMERGENCYCOLDCASE varchar(500),WARD varchar(150))
DECLARE #strSQL VARCHAR(MAX)
SET #strSQL = N'SELECT DISTINCT Upper (
CASE
WHEN Cast(i.attendantaddress AS VARCHAR(30)) IS NULL THEN i.specialnotes
ELSE Cast(i.attendantaddress AS VARCHAR(30))
END) controlno,
pm.registrationno,
rp.firstname
||'' ''
||rp.middlename
||'' ''
||rp.lastname AS patientname,
rp.age, (
CASE
WHEN rp.gender=71 THEN ''f''
ELSE ''m''
END ) gender,
ad.address1
||'',
''
||ad.address2
||'',
''
||c.cityname
||'',
''
||sm.statename adress, (
CASE
WHEN ad.residencenumber IS NULL THEN (
CASE
WHEN ad.emergencynumber IS NULL THEN ad.mobilenumber
WHEN ad.emergencynumber IS NOT NULL THEN ad.emergencynumber
WHEN ad.mobilenumber IS NULL THEN ad.emergencynumber
WHEN ad.mobilenumber IS NOT NULL THEN ad.mobilenumber
END)
ELSE ad.residencenumber
END) contactnumber,
i.inpatientno,
bm.bedcode,
i.reasonforadmission,
(
SELECT dt.parametervalue
FROM wards.dischargesummdtls dt
WHERE dt.parammappingid IN
(
SELECT pm.parammappingid
FROM wards.parametermapping pm
WHERE pm.parameterid = 1299)
AND dt.status = 1
AND dt.dischargeno IN
(
SELECT dy.dischargeno
FROM wards.dischargesumm_dync dy
WHERE dy.ipno = i.inpatientno)) diagnosis,
i.dateofadmission,
e.firstname
||'' ''
||e.middlename
||'' ''
||e.lastname AS doctor,
f_getspeciality(i.admittingdoctor) speciality,
f_getemployeename(i.referreddoctor) referreddoctor,
upper(i.wardnurse) recommendedby,
upper(i.housekeeping) emergencycoldcase,
l.leveldetailname
FROM billing.pateintpolicydetails pd
LEFT JOIN billing.patientpolicymaster pm
ON pd.policymasterid = pm.patientpolicymasterid
AND pd.policystatus = 1
AND pd.aggrementid = 60429
JOIN adt.inpatientmaster i
ON i.uhid = pm.registrationno
JOIN registration.patient rp
ON rp.uhid = i.uhid
JOIN registration.addressmaster ad
ON rp.registrationid=ad.registrationid
AND ad.addresstypeid=''2''
AND ad.status=''1''
INNER JOIN ehis.countrymaster cm
ON cm.countrycode=ad.country
INNER JOIN ehis.statemaster sm
ON sm.statecode=ad.state
AND sm.status=''1''
INNER JOIN ehis.districtmaster dm
ON dm.districtcode=ad.district
AND dm.status=''1''
AND dm.stateid=sm.stateid
INNER JOIN ehis.citymaster c
ON c.citycode=ad.city
AND c.status=''1''
AND c.districtid=dm.districtid
JOIN adt.bedmaster bm
ON bm.bedid = i.bedid
JOIN hr.employee_main_details e
ON e.employeeid = i.admittingdoctor
JOIN adt.leveldetail l
ON l.leveldetailid = bm.leveldetailid
WHERE pm.locationid = 10701
AND i.locationid = 10701
AND i.status NOT IN (7,11)
UNION
SELECT DISTINCT upper (
CASE
WHEN cast(i.attendantaddress AS varchar(30)) IS NULL THEN i.specialnotes
ELSE cast(i.attendantaddress AS varchar(30))
END) controlno,
pm.registrationno,
rp.firstname
||'' ''
||rp.middlename
||'' ''
||rp.lastname AS patientname,
rp.age, (
CASE
WHEN rp.gender=71 THEN ''f''
ELSE ''m''
END ) gender,
ad.address1
||'',
''
||ad.address2
||'',
''
||c.cityname
||'',
''
||sm.statename adress, (
CASE
WHEN ad.residencenumber IS NULL THEN (
CASE
WHEN ad.emergencynumber IS NULL THEN ad.mobilenumber
WHEN ad.emergencynumber IS NOT NULL THEN ad.emergencynumber
WHEN ad.mobilenumber IS NULL THEN ad.emergencynumber
WHEN ad.mobilenumber IS NOT NULL THEN ad.mobilenumber
END)
ELSE ad.residencenumber
END) contactnumber,
i.inpatientno,
bm.bedcode,
i.reasonforadmission,
(
SELECT dt.parametervalue
FROM wards.dischargesummdtls dt
WHERE dt.parammappingid IN
(
SELECT pm.parammappingid
FROM wards.parametermapping pm
WHERE pm.parameterid = 1299)
AND dt.status = 1
AND dt.dischargeno IN
(
SELECT dy.dischargeno
FROM wards.dischargesumm_dync dy
WHERE dy.ipno = i.inpatientno)) diagnosis,
i.dateofadmission,
e.firstname
||'' ''
||e.middlename
||'' ''
||e.lastname AS doctor,
f_getspeciality(i.admittingdoctor) speciality,
f_getemployeename(i.referreddoctor) referreddoctor,
upper(i.wardnurse) recommendedby,
upper(i.housekeeping) emergencycoldcase,
l.leveldetailname
FROM billing.pateintpolicydetails pd
FULL OUTER JOIN billing.patientpolicymaster pm
ON pd.policymasterid = pm.patientpolicymasterid
AND pd.policystatus = 1
JOIN adt.inpatientmaster i
ON i.uhid = pm.registrationno
JOIN registration.patient rp
ON rp.uhid = i.uhid
JOIN registration.addressmaster ad
ON rp.registrationid=ad.registrationid
AND ad.addresstypeid=''2''
AND ad.status=''1''
INNER JOIN ehis.countrymaster cm
ON cm.countrycode=ad.country
INNER JOIN ehis.statemaster sm
ON sm.statecode=ad.state
AND sm.status=''1''
INNER JOIN ehis.districtmaster dm
ON dm.districtcode=ad.district
AND dm.status=''1''
AND dm.stateid=sm.stateid
INNER JOIN ehis.citymaster c
ON c.citycode=ad.city
AND c.status=''1''
AND c.districtid=dm.districtid
JOIN adt.bedmaster bm
ON bm.bedid = i.bedid
JOIN hr.employee_main_details e
ON e.employeeid = i.admittingdoctor
JOIN adt.leveldetail l
ON l.leveldetailid = bm.leveldetailid
AND l.leveldetailid NOT IN (221,257)
WHERE i.freepatient = 1
AND pm.locationid = 10701
AND i.locationid = 10701
AND i.status NOT IN (7,11)
UNION
SELECT DISTINCT upper (
CASE
WHEN cast(i.attendantaddress AS varchar(30)) IS NULL THEN i.specialnotes
ELSE cast(i.attendantaddress AS varchar(30))
END) controlno,
pm.registrationno,
rp.firstname
||'' ''
||rp.middlename
||'' ''
||rp.lastname AS patientname,
rp.age, (
CASE
WHEN rp.gender=71 THEN ''f''
ELSE ''m''
END ) gender,
ad.address1
||'',
''
||ad.address2
||'',
''
||c.cityname
||'',
''
||sm.statename adress, (
CASE
WHEN ad.residencenumber IS NULL THEN (
CASE
WHEN ad.emergencynumber IS NULL THEN ad.mobilenumber
WHEN ad.emergencynumber IS NOT NULL THEN ad.emergencynumber
WHEN ad.mobilenumber IS NULL THEN ad.emergencynumber
WHEN ad.mobilenumber IS NOT NULL THEN ad.mobilenumber
END)
ELSE ad.residencenumber
END) contactnumber,
i.inpatientno,
bm.bedcode,
i.reasonforadmission,
(
SELECT dt.parametervalue
FROM wards.dischargesummdtls dt
WHERE dt.parammappingid IN
(
SELECT pm.parammappingid
FROM wards.parametermapping pm
WHERE pm.parameterid = 1299)
AND dt.status = 1
AND dt.dischargeno IN
(
SELECT dy.dischargeno
FROM wards.dischargesumm_dync dy
WHERE dy.ipno = i.inpatientno)) diagnosis,
i.dateofadmission,
e.firstname
||'' ''
||e.middlename
||'' ''
||e.lastname AS doctor,
f_getspeciality(i.admittingdoctor) speciality,
f_getemployeename(i.referreddoctor) referreddoctor,
upper(i.wardnurse) recommendedby,
upper(i.housekeeping) emergencycoldcase,
l.leveldetailname
FROM billing.pateintpolicydetails pd
FULL OUTER JOIN billing.patientpolicymaster pm
ON pd.policymasterid = pm.patientpolicymasterid
AND pd.policystatus = 1
JOIN adt.inpatientmaster i
ON i.uhid = pm.registrationno
JOIN registration.patient rp
ON rp.uhid = i.uhid
JOIN registration.addressmaster ad
ON rp.registrationid=ad.registrationid
AND ad.addresstypeid=''2''
AND ad.status=''1''
INNER JOIN ehis.countrymaster cm
ON cm.countrycode=ad.country
INNER JOIN ehis.statemaster sm
ON sm.statecode=ad.state
AND sm.status=''1''
INNER JOIN ehis.districtmaster dm
ON dm.districtcode=ad.district
AND dm.status=''1''
AND dm.stateid=sm.stateid
INNER JOIN ehis.citymaster c
ON c.citycode=ad.city
AND c.status=''1''
AND c.districtid=dm.districtid
JOIN adt.bedmaster bm
ON bm.bedid = i.bedid
JOIN hr.employee_main_details e
ON e.employeeid = i.admittingdoctor
JOIN adt.leveldetail l
ON l.leveldetailid = bm.leveldetailid
AND l.leveldetailid IN (221,257)
WHERE i.freepatient = 1
AND pm.locationid = 10701
AND i.locationid = 10701
AND i.status NOT IN (7,11)'
INSERT #temp
SELECT * FROM OPENQUERY(ahdelwards,#strSQL)
SELECT DISTINCT * FROM #temp ORDER BY 11 ASC
END
I have a SQL query that is just a union between two SELECT statements. Say the result of the overall query produces 10 records. I want as part of that result set a column that is a numeric and sequential (like a primary key - 0,1,2,3, and so on). My problem is the way I have this coded, as you can see below, doesn't produce unique values (the 0 value is repeated twice, the 1 value is repeated twice, as expected, because of the union statement). How can I get the below "Transaction Sequence Number" to display 1,2,3,4,5,6,7,8,9,10? Instead of 1,2,3,4,5,1,2,3,4,5?
Here's my code (below). I will be posting a screenshot of my result set shortly - SQL Server is being incredibly slow for me right now - I hope this makes sense without a screenshot of the result set:
select top 5
'ACCT PROMORESP' as 'Transaction Identifier',
row_number() over (order by s.HL_ACCT_ID) as 'Transaction Sequence Number',
s.HL_ACCT_ID as 'HL_Acct_ID',
null as [AcctNumber],
null as [AcctType],
null as [AcctSource],
null as [DUNS_NBR],
null as [DBPLCR_CONTACT_ID],
s.CAMPAIGNCODE as [CellCode],
'-1' as [OfferCode],
case
when c.EventDate is not null then 'Click'
when c.EventDate is null then
case
when sub.status = 'unsubscribed' then 'Unsubscribe'
when sub.status = 'bounced' then 'Bounce'
when sub.status = 'held' then 'Bounce'
end
end as [ResponseType],
convert(varchar, c.EventDate, 112) as [ResponseDate],
null as [ResponseQuantity],
null as [ResponseValue],
'Email' as [ResponseChannel],
null as [Cookie ID],
null as [IP address],
null as [Device ID],
null as [CUSTOM_TEXT_01],
null as [CUSTOM_TEXT_02],
null as [CUSTOM_TEXT_03],
null as [CUSTOM_TEXT_04],
null as [CUSTOM_TEXT_05]
from cXXXXXXX.sendlog s with (nolock)
inner join cXXXXXXX._subscribers sub with (nolock) on sub.SubscriberKey = s.Email
left join cXXXXXXX._click c with (nolock) on c.JobID = s.JobID and c.SubscriberKey = s.Email
where c.EventDate is not null or (c.EventDate is null and (sub.status = 'unsubscribed' or sub.status = 'bounced' or sub.status = 'held')) and c.isunique = 1
union all
select top 5
'ACCT PROMORESP' as 'Transaction Identifier',
(row_number() over (order by s.HL_ACCT_ID)) + 1 as 'Transaction Sequence Number',
s.HL_ACCT_ID as 'HL_Acct_ID',
null as [AcctNumber],
null as [AcctType],
null as [AcctSource],
null as [DUNS_NBR],
null as [DBPLCR_CONTACT_ID],
s.CAMPAIGNCODE as [CellCode],
'-1' as [OfferCode],
case
when o.EventDate is not null then 'Message Open'
when o.EventDate is null then
case
when sub.status = 'unsubscribed' then 'Unsubscribe'
when sub.status = 'bounced' then 'Bounce'
when sub.status = 'held' then 'Bounce'
end
end as [ResponseType],
convert(varchar, o.EventDate, 112) as [ResponseDate],
null as [ResponseQuantity],
null as [ResponseValue],
'Email' as [ResponseChannel],
null as [Cookie ID],
null as [IP address],
null as [Device ID],
null as [CUSTOM_TEXT_01],
null as [CUSTOM_TEXT_02],
null as [CUSTOM_TEXT_03],
null as [CUSTOM_TEXT_04],
null as [CUSTOM_TEXT_05]
from cXXXXXXX.sendlog s with (nolock)
inner join cXXXXXXX._subscribers sub with (nolock) on sub.SubscriberKey = s.Email
left join cXXXXXXX._open o with (nolock) on o.JobID = s.JobID and o.SubscriberKey = s.Email
where o.EventDate is not null or (o.EventDate is null and (sub.status = 'unsubscribed' or sub.status = 'bounced' or sub.status = 'held')) and o.isunique = 1
You can enclose your sql in a common table expression and then number them:
;WITH CTE AS(your sql...)
SELECT *,
(row_number() over (order by HL_ACCT_ID)) + 1 as 'Transaction Sequence Number'
FROM CTE
You have to make sure you have unique column names in the cte. Also, if you are using this sql statement with other statements, make sure you add a ';' before it or end the previous statement with a ';'.
Try using this.
SELECT ROW_NUMBER() OVER(ORDER BY DATA.HL_ACCT_ID),DATA.* FROM
(your query here...)DATA