Order By being ignored in SQL Server 2008 with multiple subqueries - sql-server

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

Related

SQL Server : restricting data range

The query below is supposed to show details for 2 types of products: DIS001 and DIS002.
When DIS002, this should "reset" the query, so that it only shows DIS001 products which were sold after that the date when DIS002 was sold.
To be honest, I'm not even sure if this is possible. I'll be grateful for any suggestions.
SELECT DISTINCT
Sales.RaisedDateTime AS [Date],
Contacts.ContactID AS [Contact ID],
Contacts.SiteID AS [Site ID],
Sales.ProductID AS [Product],
CASE
WHEN Sales.ProductID = 'DIS002'
THEN Sales.RaisedDate
ELSE CONVERT(DATETIME, CONVERT(VARCHAR(10), '2019-10-28', 101) + ' 00:00:00')
END AS [Start Date]
FROM
((Bookings.Bookings Bookings
INNER JOIN
Contacts.Contacts Contacts ON (Bookings.ContactID = Contacts.ContactID))
INNER JOIN
Sales.Sales Sales ON (Bookings.ContactID = Sales.ContactID))
WHERE
(Sales.ProductID = 'DIS001' AND
Sales.RaisedDate >= MAX([Start Date])
There are lots of different syntax's to solve this, but here is one:
;with DIS002 as (
select ContactID, max(RaisedDate) as DIS002Date
from Sales.Sales
where ProductID = 'DIS002'
group by ContactID
)
SELECT DISTINCT
Sales.RaisedDateTime AS [Date],
Contacts.ContactID AS [Contact ID],
Contacts.SiteID AS [Site ID],
Sales.ProductID AS [Product]
FROM
((Bookings.Bookings Bookings
INNER JOIN
Contacts.Contacts Contacts ON (Bookings.ContactID = Contacts.ContactID))
INNER JOIN
Sales.Sales Sales ON (Bookings.ContactID = Sales.ContactID))
LEFT JOIN
DIS002 on DIS002.ContactID = Sales.ContactID
WHERE
Sales.ProductID = 'DIS001' AND
Sales.RaisedDate >= isnull(DIS002date,'1900-01-01')

Microsoft SQL Server: how can I group by this column? GROUP BY not working for me

I want to group by Quote ID, I am not able to get it to work though. I've been banging my head on this one for a while.
EDIT: I'm trying to group the Quantity items into one column, so for example if a Quote ID column has 3 items with the same Quote ID but different quantities, I want to display them in the same row in this fashiong - $QuoteID, $QuantityFromRow1, $QuantityFromRow2, $QuantityFromRow3.
SELECT TOP(100)
PPV8.dbo.CUSTOMER.ID As [Customer ID]
, PPV8.dbo.CUSTOMER.NAME As [Customer]
, PPV8.dbo.CUSTOMER.CITY As City, Null As [PM]
, PPV8.dbo.CUSTOMER.STATE As State
, PPV8.dbo.QUOTE_PRICE.QUOTE_ID As [Quote ID]
, FLOOR(PPV8.dbo.QUOTE_PRICE.QTY) As Quantity
, PPV8.dbo.QUOTE_LINE.PART_ID As [Part ID]
, SUBSTRING(PPV8.dbo.QUOTE_LINE.CUSTOMER_PART_ID, 6, 12) As [Style #]
, PPV8.dbo.QUOTE_LINE.DESCRIPTION As Description
, PPV8.dbo.QUOTE_PRICE.UNIT_PRICE As [Unit Price]
, PPV8.dbo.QUOTE_LINE.CREATE_DATE As [Create Date]
, PPV8.dbo.QUOTE.SALESREP_ID As [Rep]
, PPV8.dbo.QUOTE.STATUS As [Quote Status]
, PPV8.dbo.QUOTE.FOLLOWUP_DATE As [Follow Up]
, PPV8.dbo.QUOTE.EXPECTED_WIN_DATE As [Due Date]
FROM
CUSTOMER
INNER JOIN
QUOTE ON PPV8.dbo.CUSTOMER.ID = PPV8.dbo.QUOTE.CUSTOMER_ID
INNER JOIN
QUOTE_LINE ON PPV8.dbo.QUOTE.ID = PPV8.dbo.QUOTE_LINE.QUOTE_ID
INNER JOIN
QUOTE_PRICE ON PPV8.dbo.QUOTE_LINE.QUOTE_ID = PPV8.dbo.QUOTE_PRICE.QUOTE_ID
AND PPV8.dbo.QUOTE_LINE.LINE_NO = PPV8.dbo.QUOTE_PRICE.QUOTE_LINE_NO
WHERE
PPV8.dbo.QUOTE.STATUS = 'A'
AND PPV8.dbo.QUOTE.EXPECTED_WIN_DATE > '20170101'
ORDER BY
PPV8.dbo.QUOTE.EXPECTED_WIN_DATE ASC
All (non aggregate) columns in the select statement must be included in the group by clause
So you are missing the point of group by

SELECTING from a UNION GETTING A JOIN ISSUE

I am trying to run the below query that would basically pull three columns from a two query UNION- I am getting the error that the multi-part identifier H.po_number on line 1 could not be bound. I know that is a JOIN issue but not sure why? The query runs perfectly on its own but when I add the first SELECT I get the JOIN issue. This is actually going to be in an INSERT statement that pulls those first three values out and stores in another table for error tracking. Any idea why that breaks it? Its format sucks right now - working on that part (captial and lowercase, etc.)
select H.po_number as [sap po number],
getdate(),
'sapnotgps' as [report_source]
from
(SELECT * FROM ( SELECT S.team_member_name as [ASSIGNED EMPLOYEE], -- Using NEW employee table
H.po_type as [PO TYPE],
G.order_no as [GPS PO #],
H.po_number as [SAP PO NUMBER],
CONVERT(VARCHAR(12),H.po_issue_date,101) AS [PO ISSUE DATE],
M.department as [DEPARTMENT],
K.business_unit_desc as [BU],
M.description as [DESCRIPTION],
M.material as [MATERIAL],
H.po_ordered_quantity as [PO QUANTITY],-- Use header ordered qty to negate multi-line po issue (do not SUM!)
MAX(P.comment) as [PO COMMENT],
MIN(CONVERT(VARCHAR(12),E.[date],101)) as [FIRST SHOWN ON RPT]
from (
select order_no, order_status, cst_order_no, status_date,last_conf_date_cst
from asagdwpdx_prod.dbo.SimoxOrder1
union all
select order_no, order_status, cst_order_no, status_date,last_conf_date_cst
from asagdwpdx_prod.dbo.SimoxOrder2
union all
select order_no, order_status, cst_order_no, status_date,last_conf_date_cst
from asagdwpdx_prod.dbo.SimoxOrder3
) G
join pdx_sap_user.dbo.vw_po_header H
on G.order_no = H.ahag_number
join pdx_sap_user.dbo.vw_po_item P
on H.po_number = P.po_number
join pdx_sap_user.dbo.vw_mm_material M
on P.material = M.material
join pdx_sap_user.dbo.vw_kd_business_unit K
on M.business_unit_code = K.business_unit_code
join adi_user_maintained.dbo.scm_po_employee_name S
on S.po_number = P.po_number
join adi_user_maintained.dbo.scm_po_error_tracking E
on H.po_number = E.po_number
where G.order_status <> '90'
and not exists (
select 1
from pdx_sap_user.dbo.vw_po_item i
where i.po_number = H.po_number
and (i.del_indicator <> 'L' or i.del_indicator is null
and M.business_segment_code not in ('421','420','422','424'))) --exclude adi golf
group by G.order_no,
G.last_conf_date_cst,
H.po_number,
H.po_issue_date,
M.material,
M.[description],
K.business_unit_desc,
M.department,
H.po_created_by,
S.team_member_name,
H.po_type,
H.po_ordered_quantity
) AS C
UNION ALL
(SELECT
S.team_member_name AS [ASSIGNED EMPLOYEE],
H.po_type AS [PO TYPE],
G.order_no AS [GPS PO #],
H.po_number AS [SAP PO NUMBER],
CONVERT(VARCHAR(12),H.po_issue_date,101) AS [PO ISSUE DATE],
M.department AS [DEPARTMENT],
K.business_unit_desc AS [BU],
M.[description] AS [DESCRIPTION],
P.material AS [MATERIAL],
P.po_ordered_quantity AS [PO QUANTITY],
P.comment AS [PO COMMENT],
MIN(CONVERT(VARCHAR(12),E.[date],101)) AS [FIRST SHOWN ON RPT]
FROM pdx_sap_user.dbo.vw_po_header H
JOIN pdx_sap_user.dbo.vw_po_item P
ON H.po_number = P.po_number
JOIN pdx_sap_user.dbo.vw_mm_material M
ON P.material = M.material
JOIN pdx_sap_user.dbo.vw_kd_business_unit K
ON M.business_unit_code = K.business_unit_code
JOIN adi_user_maintained.dbo.scm_po_employee_name S
ON H.po_number = S.po_number
JOIN adi_user_maintained.dbo.scm_po_error_tracking E
ON H.po_number = E.po_number
JOIN
(SELECT order_no,
order_status,
status_date,
right(cst_order_no,10) as [cst_order_no_10],
last_conf_date_cst,
cst_order_no
FROM asagdwpdx_prod.dbo.SimoxOrder1
UNION ALL
SELECT order_no,
order_status,
status_date,
right(cst_order_no,10) as [cst_order_no_10],
last_conf_date_cst,
cst_order_no
FROM asagdwpdx_prod.dbo.SimoxOrder2
UNION ALL
SELECT order_no,
order_status,
status_date,
right(cst_order_no,10) as [cst_order_no_10],
last_conf_date_cst,
cst_order_no
FROM asagdwpdx_prod.dbo.SimoxOrder3) G
ON P.po_number = G.cst_order_no_10
WHERE H.ahag_number LIKE '0%'
AND G.order_status <> '90'
AND NOT EXISTS (
SELECT 1
FROM pdx_sap_user.dbo.vw_po_item i
WHERE i.po_number = H.po_number
AND (i.del_indicator <> 'L' or i.del_indicator IS NULL --find ONLY PO's where all lines are L
AND M.business_segment_code NOT IN ('421','420','422','424'))) --exclude adi golf
GROUP BY S.team_member_name,
H.po_type,
G.order_no,
H.po_number,
H.po_issue_date,
G.last_conf_date_cst,
M.department,
K.business_unit_desc,
M.[description],
P.material,
P.po_ordered_quantity,
P.comment)) AS D;
The alias h has "expired" (and replaced by the alias "d") in the topmost select clause. Additionally all the column aliases you have used through the subqueries are also now active. So your final select should look more like this:
SELECT
GETDATE()
, 'sapnotgps' AS [report_source]
, d.[assigned employee]
, d.[po type]
, d.[gps po #]
, d.[sap po number]
, d.[po issue date]
, d.[department]
, d.[bu]
, d.[description]
, d.[material]
, d.[po quantity]
, d.[po comment]
, d.[first shown on rpt]
or without the alias d:
SELECT
GETDATE()
, 'sapnotgps' AS [report_source]
, [assigned employee]
, [po type]
, [gps po #]
, [sap po number]
, [po issue date]
, [department]
, [bu]
, [description]
, [material]
, [po quantity]
, [po comment]
, [first shown on rpt]
FROM (
SELECT
*
FROM (
SELECT
s.team_member_name AS [assigned employee]
-- Using NEW employee table
, h.po_type AS [po type]
, g.order_no AS [gps po #]
, h.po_number AS [sap po number]
, CONVERT(varchar(12), h.po_issue_date, 101) AS [po issue date]
, m.department AS [department]
, k.business_unit_desc AS [bu]
, m.description AS [description]
, m.material AS [material]
, h.po_ordered_quantity AS [po quantity]
-- Use header ordered qty to negate multi-line po issue (do not SUM!)
, MAX(p.comment) AS [po comment]
, MIN(CONVERT(varchar(12), e.[date], 101)) AS [first shown on rpt]
FROM (
SELECT
order_no
, order_status
, cst_order_no
, status_date
, last_conf_date_cst
FROM asagdwpdx_prod.dbo.SimoxOrder1
UNION ALL
SELECT
order_no
, order_status
, cst_order_no
, status_date
, last_conf_date_cst
FROM asagdwpdx_prod.dbo.SimoxOrder2
UNION ALL
SELECT
order_no
, order_status
, cst_order_no
, status_date
, last_conf_date_cst
FROM asagdwpdx_prod.dbo.SimoxOrder3
) g
JOIN pdx_sap_user.dbo.vw_po_header h ON g.order_no = h.ahag_number
JOIN pdx_sap_user.dbo.vw_po_item p ON h.po_number = p.po_number
JOIN pdx_sap_user.dbo.vw_mm_material m ON p.material = m.material
JOIN pdx_sap_user.dbo.vw_kd_business_unit k ON m.business_unit_code = k.business_unit_code
JOIN adi_user_maintained.dbo.scm_po_employee_name s ON s.po_number = p.po_number
JOIN adi_user_maintained.dbo.scm_po_error_tracking e ON h.po_number = e.po_number
WHERE g.order_status <> '90'
AND NOT EXISTS (
SELECT
1
FROM pdx_sap_user.dbo.vw_po_item i
WHERE i.po_number = h.po_number
AND (i.del_indicator <> 'L'
OR i.del_indicator IS NULL
AND m.business_segment_code NOT IN ('421', '420', '422', '424'))
) --exclude adi golf
GROUP BY
g.order_no
, g.last_conf_date_cst
, h.po_number
, h.po_issue_date
, m.material
, m.[description]
, k.business_unit_desc
, m.department
, h.po_created_by
, s.team_member_name
, h.po_type
, h.po_ordered_quantity
) AS c
UNION ALL
(SELECT
s.team_member_name AS [assigned employee]
, h.po_type AS [po type]
, g.order_no AS [gps po #]
, h.po_number AS [sap po number]
, CONVERT(varchar(12), h.po_issue_date, 101) AS [po issue date]
, m.department AS [department]
, k.business_unit_desc AS [bu]
, m.[description] AS [description]
, p.material AS [material]
, p.po_ordered_quantity AS [po quantity]
, p.comment AS [po comment]
, MIN(CONVERT(varchar(12), e.[date], 101)) AS [first shown on rpt]
FROM pdx_sap_user.dbo.vw_po_header h
JOIN pdx_sap_user.dbo.vw_po_item p ON h.po_number = p.po_number
JOIN pdx_sap_user.dbo.vw_mm_material m ON p.material = m.material
JOIN pdx_sap_user.dbo.vw_kd_business_unit k ON m.business_unit_code = k.business_unit_code
JOIN adi_user_maintained.dbo.scm_po_employee_name s ON h.po_number = s.po_number
JOIN adi_user_maintained.dbo.scm_po_error_tracking e ON h.po_number = e.po_number
JOIN (
SELECT
order_no
, order_status
, status_date
, RIGHT(cst_order_no, 10) AS [cst_order_no_10]
, last_conf_date_cst
, cst_order_no
FROM asagdwpdx_prod.dbo.SimoxOrder1
UNION ALL
SELECT
order_no
, order_status
, status_date
, RIGHT(cst_order_no, 10) AS [cst_order_no_10]
, last_conf_date_cst
, cst_order_no
FROM asagdwpdx_prod.dbo.SimoxOrder2
UNION ALL
SELECT
order_no
, order_status
, status_date
, RIGHT(cst_order_no, 10) AS [cst_order_no_10]
, last_conf_date_cst
, cst_order_no
FROM asagdwpdx_prod.dbo.SimoxOrder3
) g ON p.po_number = g.cst_order_no_10
WHERE h.ahag_number LIKE '0%'
AND g.order_status <> '90'
AND NOT EXISTS (
SELECT
1
FROM pdx_sap_user.dbo.vw_po_item i
WHERE i.po_number = h.po_number
AND (i.del_indicator <> 'L'
OR i.del_indicator IS NULL --find ONLY PO's where all lines are L
AND m.business_segment_code NOT IN ('421', '420', '422', '424'))
) --exclude adi golf
GROUP BY
s.team_member_name
, h.po_type
, g.order_no
, h.po_number
, h.po_issue_date
, g.last_conf_date_cst
, m.department
, k.business_unit_desc
, m.[description]
, p.material
, p.po_ordered_quantity
, p.comment)
) AS d;
just replace
select H.po_number as [sap po number],
getdate(),
'sapnotgps' as [report_source]
with
select D.[SAP PO NUMBER],
getdate(),
'sapnotgps' as [report_source]
Thanks.

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

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.

how do i use a temporary date table combine with three other Tables to extract all customer info using T-SQL

i want to Write a query using the temporary date table to show rows for every customer for every month since the month they first purchased from us. The table should detail the customer ID, customer name, month, Date of first Purchase, Units Purchased that month, Value Purchased that month, Cumulative Units Purchased, Cumulative Value Purchased and the Days since last purchase and the last day of the month.
i've tried this code
select c.Id AS CustomerId
,c.FirstName+' '+c.LastName as CustomerName
,DATENAME(MM,d.OrderDate) AS MonthofFirstPurchase
--,sum(d.TotalAmount) AS CummulativeValue
,d.OrderDate AS DateOfFirstPurchase
,Datediff(dd,o.OrderDate,getdate()) as DateSinceLastPurchase
from[dbo].[Customer]c inner join [dbo].[Order] b on b.CustomerId = c.Id
join (select max(Id) as OrderId, min(Id) as minOrder,[CustomerId] from [dbo].[Order] group by [CustomerId])conn on c.Id = conn.[CustomerId]
join [dbo].[Order]o on o.[Id] = conn.OrderId
join [dbo].[Order]d on d.[Id] = conn.minOrder
--join [dbo].[OrderItem]b on = conn.OrderId
but i keep getting errors i am a beginner at this
Please note that I did not execute the query.
If you do not want that column please try the below query. I did not execute the query though
;WITH CTE_Temp
AS
(
SELECT max(Id) AS OrderId
, min(Id) AS minOrder
, [CustomerId]
FROM [dbo].[Order]
GROUP BY [CustomerId]
)
SELECT c.Id AS CustomerId
, c.FirstName + ' ' + c.LastName AS CustomerName
, DATENAME(MM, d.OrderDate) AS MonthofFirstPurchase
--,sum(d.TotalAmount) AS CummulativeValue
, d.OrderDate AS DateOfFirstPurchase
, Datediff(dd, o.OrderDate, getdate()) AS DateSinceLastPurchase
FROM [dbo].[Customer] c
INNER JOIN [dbo].[Order] b ON b.CustomerId = c.Id
INNER JOIN CTE_Temp conn ON c.Id = conn.[CustomerId]
INNER JOIN [dbo].[Order] o ON o.[Id] = conn.OrderId
INNER JOIN [dbo].[Order] d ON d.[Id] = conn.minOrder
If you need the sum(d.TotalAmount) AS CummulativeValue. Just try the query
;WITH CTE_Temp
AS
(
SELECT max(Id) AS OrderId
, min(Id) AS minOrder
, [CustomerId]
FROM [dbo].[Order]
GROUP BY [CustomerId]
),
CTE_TEMP1
AS
(
SELECT CTE_Temp.[CustomerId], sum(d.TotalAmount) TotalAmount AS CummulativeValue
FROM [dbo].[Order] d INNER JOIN CTE_Temp ON d.[Id] = CTE_Temp.minOrder
GROUP BY CTE_TEMP.[CustomerId]
)
SELECT c.Id AS CustomerId
, c.FirstName + ' ' + c.LastName AS CustomerName
, DATENAME(MM, d.OrderDate) AS MonthofFirstPurchase
,CTE_TEMP1.TotalAmount AS CummulativeValue
, d.OrderDate AS DateOfFirstPurchase
, Datediff(dd, o.OrderDate, getdate()) AS DateSinceLastPurchase
FROM [dbo].[Customer] c
INNER JOIN [dbo].[Order] b ON b.CustomerId = c.Id
INNER JOIN CTE_Temp conn ON c.Id = conn.[CustomerId]
INNER JOIN [dbo].[Order] o ON o.[Id] = conn.OrderId
INNER JOIN CTE_TEMP1 d ON d.CustomerId = c.id
I have modified the anser provided by Gopakumar and i came to the solution of the problem. The code below works perfectly well for its purpose
;WITH CTE_Temp
AS
(
SELECT max(Id) AS MaxOrder
, min(Id) AS MinOrder
, [CustomerId]
FROM [dbo].[Order]
GROUP BY [CustomerId]
),
CTE_TEMP1 AS(SELECT CTE_TEMP.CustomerId,sum([UnitQuantity]) AS UnitsPurchasedForMonth,sum(TotalAmount) AS ValueForMonth
from [dbo].[OrderItem]p left outer join [dbo].[Order] e on p.Id = e.Id
INNER JOIN CTE_Temp ON e.[Id] = CTE_Temp.minOrder GROUP BY CTE_TEMP.CustomerId),
CTE_TEMP2 AS(SELECT e.CustomerId,sum([UnitQuantity]) AS CummulativeUnitsPurchased,sum(TotalAmount) AS CummulativeValue
from [dbo].[OrderItem]p inner join [dbo].[Order] e on p.Id = e.Id group by e.CustomerId)
SELECT c.Id AS CustomerId
, c.FirstName + ' ' + c.LastName AS CustomerName
, DATENAME(MM, o.OrderDate) AS MonthofFirstPurchase
, o.OrderDate AS DateOfFirstPurchase
,d.ValueForMonth AS ValuePurchasedForMonth
,d.UnitsPurchasedForMonth
,e.CummulativeUnitsPurchased
,e.CummulativeValue
, Datediff(dd, a.OrderDate, getdate()) AS DateSinceLastPurchase
,EOMONTH(o.OrderDate) AS LastDayOfMonth
FROM [dbo].[Customer] c
INNER JOIN CTE_Temp conn ON c.Id = conn.CustomerId
INNER JOIN [dbo].[Order] o ON o.[Id] = conn.MinOrder
INNER JOIN CTE_TEMP1 d ON d.CustomerId = c.id
INNER JOIN [dbo].[Order] a on a.Id = conn.MaxOrder
inner join CTE_TEMP2 e on c.Id = e.CustomerId
you can edit as you like to get your results

Resources