SELECTING from a UNION GETTING A JOIN ISSUE - sql-server

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.

Related

Using ROW_NUMBER() to remove duplicates in SQL server

My current query returns too many lines per Subject_ID, so I want to use ROW_NUMBER() to limit the resulting set to 1 line per Subject_ID. I've added this line to my SELECT statement:
, ROW_NUMBER() over(partition by CS.Subject_ID order by CS.Subject_ID) rn
But when I try to put WHERE rn = 1 anywhere in the FROM statement, I get the error:
Incorrect syntax near the keyword 'WHERE'
And when I try to change it to AND rn = 1 (and add it on to another AND/OR line) I get the error:
Invalid column name 'rn'
So my first question is: When I add a field to my SELECT statement using that ROW_NUMBER() line, what table does this column belong to? Do I need to append it to something like Table.rn? My second question is where should I put this rn = 1 line and how should I write it in?
Full query:
SELECT
Groups.Group_Name
, CT.Created
, CT.Subject_Id
INTO #temp
FROM SubjectZ_Task CT
INNER JOIN
SubjectZ_Task_Users On CT.SubjectZ_Task_Id = SubjectZ_Task_Users.SubjectZ_Task_Id
INNER JOIN
Groups ON Groups.Group_ID = SubjectZ_Task_Users.Group_Reference
WHERE Group_Name LIKE 'Team 1'
AND CT.Created >= '1/1/2019' AND CT.Created < DATEADD(Day,1,'12/31/2019')
GROUP BY Groups.group_name, CT.Created, CT.Subject_ID
SELECT
CT.Group_Name
, CT.Created
, CS.Topic_Start_Date
, CS.Subject_ID
, P.FirstName
, P.LastName
, CS.Subject_Match_ID
, SubjectX.Firstname AS SubjectX_firstname
, CS.SubjectY
, AEC.AEC AS Max_AEC
, SubjectX.Email_id As SubjectX_Email
, Phone.Phone
, ROW_NUMBER() over(partition by CS.Subject_ID order by CS.Subject_ID) rn
FROM #temp CT
LEFT JOIN QE_Topic_Summary CS ON CS.Subject_ID = CT.Subject_Id
AND (Topic_Status LIKE 'In Progress'
OR Topic_Status LIKE 'Pending')
AND CS.Topic_Start_Date >= DATEADD(Day,-60,CT.Created) AND CS.Topic_Start_Date <= DATEADD(Day,60,CT.Created)
INNER JOIN Subjects P ON P.Subject_ID = CS.Subject_ID
LEFT JOIN Subjects SubjectX ON SubjectX.Subject_ID = CS.SubjectX_ID
LEFT JOIN QE_TB_MAX_AEC AEC ON AEC.Subject_ID = CS.Subject_ID
INNER JOIN Subject_Identifiers PI ON PI.Subject_ID = P.Subject_ID
LEFT JOIN Subject_Identifiers PIP ON PIP.Subject_ID = SubjectX.Subject_ID
LEFT JOIN Subject_Phone Phone On Phone.Subject_ID = P.Subject_ID WHERE Phone.Voice = 1
drop table #temp
I don't see a reference to rn in your WHERE clause, but my guess is that you need to wrap it in another query like so:
SELECT *
FROM(
SELECT
CT.Group_Name
, CT.Created
, CS.Topic_Start_Date
, CS.Subject_ID
, P.FirstName
, P.LastName
, CS.Subject_Match_ID
, SubjectX.Firstname AS SubjectX_firstname
, CS.SubjectY
, AEC.AEC AS Max_AEC
, SubjectX.Email_id As SubjectX_Email
, Phone.Phone
, ROW_NUMBER() over(partition by CS.Subject_ID order by CS.Subject_ID) rn
FROM #temp CT
LEFT JOIN QE_Topic_Summary CS ON CS.Subject_ID = CT.Subject_Id
AND (Topic_Status LIKE 'In Progress'
OR Topic_Status LIKE 'Pending')
AND CS.Topic_Start_Date >= DATEADD(Day,-60,CT.Created) AND CS.Topic_Start_Date <= DATEADD(Day,60,CT.Created)
INNER JOIN Subjects P ON P.Subject_ID = CS.Subject_ID
LEFT JOIN Subjects SubjectX ON SubjectX.Subject_ID = CS.SubjectX_ID
LEFT JOIN QE_TB_MAX_AEC AEC ON AEC.Subject_ID = CS.Subject_ID
INNER JOIN Subject_Identifiers PI ON PI.Subject_ID = P.Subject_ID
LEFT JOIN Subject_Identifiers PIP ON PIP.Subject_ID = SubjectX.Subject_ID
LEFT JOIN Subject_Phone Phone On Phone.Subject_ID = P.Subject_ID
WHERE Phone.Voice = 1
)t
WHERE t.rn = 1

Error with Varchar to Numeric

For background: this works fine without the addition of the 'E' Table in production.
I am trying to execute the below query but am getting the error:
Msg 8114, Level 16, State 5, Line 10
Error converting data type varchar to numeric.
The odd thing is that it executes fine on our test DB - not seeing anything trying to convert to numeric so a bit baffled. Not really sure what would cause that difference as I assume data types are the same in the test DB and the production DB - any ideas?
Thanks.
/* - adding po balance qty causes duplicates
- adding stock category causes duplicates
- added PO comments using MAX function to return only first comment - gets rid of duplicates*/
/* Using NEW employee table as of 11/2 */
SELECT
S.team_member_name AS [ASSIGNED EMPLOYEE], --Using new employee table - only on bus unit as of 11/2
H.po_type AS [ PO TYPE],
G.order_no AS [GPS PO #],
P.po_number AS [SAP PO NUMBER],
M.department AS [DEPARTMENT],
G.order_qty AS [GPS QTY],
SUM(P.po_ordered_quantity) AS [SAP QUANTITY],
(SUM(P.po_ordered_quantity) - G.order_qty) AS [DIFFERENCE],
G.last_conf_date_cst AS [LAST CONFIRMED DATE],
K.business_unit_desc AS [BU],
M.[description] AS [DESCRIPTION],
P.material AS [MATERIAL],
MAX(P.comment) AS [PO COMMENT],
MIN(E.date) AS [FIRST SHOWN ON RPT]
FROM
(SELECT
order_no, order_qty, order_status,
last_conf_date_cst
FROM
asagdwpdx_prod.dbo.SimoxOrder1
UNION ALL
SELECT
order_no, order_qty, order_status,
last_conf_date_cst
FROM
asagdwpdx_prod.dbo.SimoxOrder2
UNION ALL
SELECT
order_no, order_qty, order_status,
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
adi_user_maintained.dbo.SCM_PO_Employee_Name S ON P.po_number = S.po_number
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_error_tracking E ON E.po_number = P.po_number
WHERE
M.business_segment_code NOT IN ('421', '420', '422', '424') --exclude adi golf
AND E.report_source = 'gpsvssap_qty'
GROUP BY
G.order_no, -- GROUP BY needed on aggregate function in SELECT
G.order_qty,
G.order_status,
P.po_number,
P.material,
P.del_indicator,
H.po_created_by,
M.[description],
M.department,
S.team_member_name,
K.business_unit_desc,
G.last_conf_date_cst,
H.po_type
HAVING
G.order_qty <> SUM(P.po_ordered_quantity)
AND G.order_status NOT IN ('60', '90') -- excluding GPS cancelled (90) & shipped (60) - do we need to exclude other status'?
AND P.del_indicator <> 'L'
You might want to look at 'MAX(P.comment)'. You cant find Max of string. Unless your comment is numeric

SQL Server 2008 - Not Always Getting Max

I have a query that should return the MAX CloseDate from a table that has many close dates, grouped by the ShipmentNumber column.
I seem to be getting more than one ShipmentNumber in the results when I include the Notes column.
table WorkOrders
WorkOrderID, ProjectNumber, ShipmentNumber, CloseDate, WorkOrderNotes
1, 884, 123-01, 2016-04-01, Note A
2, 884, 123-01, 2016-04-02, Note B
3, 884, 123-02, 2016-04-01, Note A
table Projects
ProjectNumber, Name
884, Project A
Query:
SELECT p.id, p.name, WO.ShipmentNumber,MAX(WO.CloseDate) AS CloseDate,
CAST(WO.WorkOrderNotes AS NVARCHAR(100)) AS WorkOrderNotes
FROM DA.dbo.WorkOrders AS WO
LEFT JOIN Projects.dbo.project_primary AS p ON p.id = WO.ProjectNumber
WHERE WO.CloseDate >= '2016-03-01'
AND WO.CloseDate IS NOT NULL
GROUP BY WO.ShipmentNumber, p.name, p.id, CAST(WO.WorkOrderNotes AS NVARCHAR(100)) ;
Results:
884, Project A, 123-01, 2016-04-01, Note A <-- Should not be here
884, Project A, 123-01, 2016-04-02, Note B
884, Project A, 123-02, 2016-04-01, Note A
#Irb got this in the comments; you're grouping by WO.ShipmentNumber and have different values for this for the first and third line; thus getting both.
If you want only the WO record with the max close date, try this:
SELECT p.id
, p.name
, WO.ShipmentNumber
, WO.CloseDate
FROM (
select ProjectNumber
, ShipmentNumber
, CloseDate
, CAST(WorkOrderNotes AS NVARCHAR(100)) AS WorkOrderNotes
, row_number() over (partition by ProjectNumber order by CloseDate desc) r
from DA.dbo.WorkOrders
WHERE WO.CloseDate >= '2016-03-01'
AND WO.CloseDate IS NOT NULL
) AS WO
LEFT JOIN Projects.dbo.project_primary AS p
ON p.id = WO.ProjectNumber
WHERE WO.r = 1 --only return the record with the most max CloseDate
GROUP BY p.id
, p.name
, WO.ShipmentNumber
, WO.WorkOrderNotes

How to select the records without duplicating form inner join tables

From this query how can I get the records without duplicate value.
I need to get the values, if the name from the table a and account from the table c should view when the dates field is maximum.
SELECT
a.name
, a.dates
, b.da
, a.id
, b.client
, b.[Address]
, b.[City]
, b.[State]
, b.dot
, b.Score
, b.Pay
, b.code
, b.[Country]
FROM a
INNER JOIN c ON a.Account = c.Account
INNER JOIN b ON [a].name = b.name
WHERE c.users = 00
AND b.Act = 1
ORDER BY a.dates
Use DISTINCT ?
SELECT DISTINCT
a.name
, a.dates
, b.da
, a.id
, b.client
, b.[Address]
, b.[City]
, b.[State]
, b.dot
, b.Score
, b.Pay
, b.code
, b.[Country]
FROM a
INNER JOIN c ON a.Account = c.Account
INNER JOIN b ON [a].name = b.name
WHERE c.users = 00
AND b.Act = 1
ORDER BY a.dates
How about using CTE ?
with CTE_duplicate
as
(SELECT
a.name
, a.dates
, b.da
, a.id
, b.client
, b.[Address]
, b.[City]
, b.[State]
, b.dot
, b.Score
, b.Pay
, b.code
, b.[Country]
, row_number() over ( partition by a.name
, a.dates
, b.da
, a.id
, b.client
, b.[Address]
, b.[City]
, b.[State]
, b.dot
, b.Score
, b.Pay
, b.code
, b.[Country] order by a.name
, a.dates
, b.da
, a.id
, b.client
, b.[Address]
, b.[City]
, b.[State]
, b.dot
, b.Score
, b.Pay
, b.code
, b.[Country] ) as rownumber
FROM a
INNER JOIN c ON a.Account = c.Account
INNER JOIN b ON [a].name = b.name
WHERE c.users = 00
AND b.Act = 1
) select * from CTE_duplicate where rownumber=1 order by dates;

Order By being ignored in SQL Server 2008 with multiple subqueries

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

Resources