Union Subquery produces Results Non-Unioned Subquery doesn't - sql

I'm using Access 2010 and i'm having a very strange query result.
I've created a query that includes a union subquery that produces results. I've also created a query that has a non-unioned subquery that doesn't produce any records. It's very strange because the union subquery is the non-unioned subquery twice.
Non-Unioned Subquery:
SELECT NVP, [NVP NAME], MIN([CURRENT PERIOD]) AS [MIN PERIOD], [BASE PERIOD]
FROM AGGDATA
GROUP BY [NVP NAME],NVP,[BASE PERIOD]
Unioned Subquery:
SELECT NVP, [NVP NAME], MIN([CURRENT PERIOD]) AS [MIN PERIOD], [BASE PERIOD]
FROM AGGDATA
GROUP BY [NVP NAME],NVP,[BASE PERIOD]
UNION
SELECT NVP, [NVP NAME], MIN([CURRENT PERIOD]) AS [MIN PERIOD], [BASE PERIOD]
FROM AGGDATA
GROUP BY [NVP NAME],NVP,[BASE PERIOD]
Here is the whole Query:
SELECT sub.NVP,sub.[NVP NAME], SUB.[MIN PERIOD], SUB.[BASE PERIOD], TT.[ACTIVE PERIODS]
FROM
(SELECT AGGD.NVP, AGGD.[NVP NAME], MIN(AGGD.[CURRENT PERIOD]) AS [MIN PERIOD], [BASE PERIOD]
FROM AGGDATA AGGD
GROUP BY AGGD.[NVP NAME],AGGD.NVP,[BASE PERIOD]
UNION
SELECT AGGD.NVP, AGGD.[NVP NAME], MIN(AGGD.[CURRENT PERIOD]) AS [MIN PERIOD], [BASE PERIOD]
FROM AGGDATA AGGD
GROUP BY AGGD.[NVP NAME],AGGD.NVP,[BASE PERIOD])
AS SUB
INNER JOIN
(SELECT SUB.NVP,
SUB.[BASE PERIOD],
COUNT([CURRENT PERIOD]) AS [ACTIVE PERIODS]
FROM
(SELECT DISTINCT NVP, [BASE PERIOD], [CURRENT PERIOD]
FROM AGGDATA)
AS SUB
GROUP BY SUB.NVP, SUB.[BASE PERIOD]
having COUNT([CURRENT PERIOD]) < 10)
AS TT
ON SUB.[BASE PERIOD] = TT.[BASE PERIOD] AND SUB.NVP = TT.NVP
WHERE SUB.[MIN PERIOD] > TT.[BASE PERIOD]
Does anyone know why the Union subquery works but the non-unioned subquery doesn't?
EDIT: The two subqueries do produce the same results, the issue is with the whole query.
Thank you!

I think you have some issues with your parentheses and aliases. Try this code instead:
SELECT
mn.NVP,[NVP NAME], [MIN PERIOD], mn.[BASE PERIOD], TT.[ACTIVE PERIODS]
FROM
(SELECT
[NVP NAME],NVP,[BASE PERIOD], MIN([CURRENT PERIOD]) AS [MIN PERIOD]
FROM
AGGDATA
GROUP BY
[NVP NAME],NVP,[BASE PERIOD]) AS mn INNER JOIN
(SELECT
NVP,
[BASE PERIOD],
COUNT([CURRENT PERIOD]) AS [ACTIVE PERIODS]
FROM
(SELECT DISTINCT
NVP, [BASE PERIOD], [CURRENT PERIOD]
FROM
AGGDATA) AS a
GROUP BY
NVP, [BASE PERIOD]
HAVING
COUNT([CURRENT PERIOD]) < 10) AS TT ON
mn.[BASE PERIOD] = TT.[BASE PERIOD] AND
mn.NVP = TT.NVP
WHERE
mn.[MIN PERIOD] > TT.[BASE PERIOD]

Related

Why does my record count increase as my denominator for a division performed in a nested query increases?

In my query I'm trying to calculate the total overtime worked by employees by dividing basic salary by 173(hours in a month) which gives me the hourly rate then dividing the total overtime amount of employee by the hourly rate. To my surprise the record count increases as the number of hours in a month increases, should it not decrease?
Here's my script:
select 'Employees that worked more overtime' [CAAT],*
from ( select H.[Month]
,H.[Employee Code]
,H.[Department]
,H.[Job title]
,H.[Surname]
,H.[Full Names]
,H.[Basic Salary]
,R.[Overtime]
,H.[Hourly Rate]
,round(R.[Overtime] / H.[Hourly Rate],2) [Overtime Hours]
from (select [Month]
,[Employee Code]
,Department
,[Job title]
,[Surname]
,[Full Names]
,nullif(convert(money,[Amount]),0.00) [Basic Salary]
,nullif(round(convert(money,[Amount]) / 173,2),0.00) [Hourly Rate]
from [Salary DB]
where [Field Desc] = 'ED01-Basic Salary') H
left join
(select [Month]
,[Employee Code]
,nullif(sum(convert(money,[Amount])),0.00) [Overtime]
from [Salary DB]
where [Field Desc] in ('ED02-O/Time 1.5','ED02-O/Time 2.0','ED42-Sunday Pay')
group by [Month]
,[Employee Code]) R
on H.[Employee Code] = R.[Employee Code]
and H.[Month] = R.[Month]) [Data]
where [Overtime Hours] > '40'
Order by [Employee Code], [Month] Desc

Performance issue with SQL Query

I am pulling data from two tables-Forecast and Orders to compute sales forecast accuracy.
Steps I am taking:
Identifying all exhaustive combinations of product-region-demand month b/w both data sets...let's call this (1)
Identifying different forecast snapshots in forecast data... let's call this (2)
Performing a cross-join of (1) and (2)...let's call this (3)
Performing the "SUMIF()" equivalent on the lines from (3) for both orders and forecast. For example, if I am comparing forecast to actual orders for February,
Jan "INDPOR" Forecast---> For some Product/Region-Feb Delivery Combination: February Forecast (generated in January) vs. Orders booked after Jan 1st with a delivery schedule in Feb
Feb "INDPOR" Forecast---> For the same Product/Region-Feb Delivery Date Combination: February Forecast (generated in February) vs. Orders booked after Jan 27th* with a delivery schedule in Feb
Note 1: Generating multiple forecasts for the same month
Note 2: Fiscal calendar definitions used; that is why Feb starts on Jan 27th
Output is generating correctly. But, it is painfully slow (1 hour +). Please help me fine-tune this and make it faster as I will need to use this for larger data sets too.
Other Details:
I am running this on SQL Server 2014 locally from my desktop.Uploading this using the SQL data import wizard into SQL from an Excel file currently
Input Forecast data: ForecastAggTable
Input Orders data: OrderAggTable
Input and Output Files
Code:
Select *
from
(
Select *,
(Select isnull(sum([Forecast Qty]),0) from ForecastAggTable t2 where t2.LOB=D.LOB and
t2.[Demand Month]=D.[Demand Month] and t2.Class=D.Class
and t2.[Item Type]=D.[Item Type] and t2.[LoB Region]=D.[LoB Region] and
t2.[Key Account]=D.[Key Account] and t2.Country=D.Country
and t2.[Master Customer]=D.[Master Customer] and t2.[INDPOR Version]=D.[INDPOR Version])[Forecast Qty],
(
Select isnull(sum([Order Qty]),0) from OrderAggTable t1 where t1.LOB=D.LOB and
t1.[SAD Month]=D.[Demand Month] and t1.Class=D.Class
and t1.[Item Type]=D.[Item Type] and t1.[LoB Region]=D.[LoB Region] and
t1.[Key Account]=D.[Key Account] and t1.Country=D.Country
and t1.[Master Customer]=D.[Master Customer] and t1.[Book Date]>=D.[INDPOR Timestamp]
)[SAD-OrderQty],
(
Select isnull(sum([Order Revenue]),0) from OrderAggTable t1 where t1.LOB=D.LOB and
t1.[SAD Month]=D.[Demand Month] and t1.Class=D.Class
and t1.[Item Type]=D.[Item Type] and t1.[LoB Region]=D.[LoB Region] and
t1.[Key Account]=D.[Key Account] and t1.Country=D.Country
and t1.[Master Customer]=D.[Master Customer] and t1.[Book Date]>=D.[INDPOR Timestamp]
)[SAD-OrderRevenue],
(
Select isnull(sum([Order Qty]),0) from OrderAggTable t1 where t1.LOB=D.LOB and
t1.[RDD Month]=D.[Demand Month] and t1.Class=D.Class
and t1.[Item Type]=D.[Item Type] and t1.[LoB Region]=D.[LoB Region] and
t1.[Key Account]=D.[Key Account] and t1.Country=D.Country
and t1.[Master Customer]=D.[Master Customer] and t1.[Book Date]>=D.[INDPOR Timestamp]
)[RDD-OrderQty],
(
Select isnull(sum([Order Revenue]),0) from OrderAggTable t1 where t1.LOB=D.LOB and
t1.[RDD Month]=D.[Demand Month] and t1.Class=D.Class
and t1.[Item Type]=D.[Item Type] and t1.[LoB Region]=D.[LoB Region] and
t1.[Key Account]=D.[Key Account] and t1.Country=D.Country
and t1.[Master Customer]=D.[Master Customer] and t1.[Book Date]>=D.[INDPOR Timestamp]
)[RDD-OrderRevenue]
from
(
Select distinct LOB,[INDPOR Version],[INDPOR Timestamp],[Demand Month],
[Demand Quarter],[Min Date],Class,[Item Type],[Offer PF],
[LoB Region],[Key Account],Country,[Master Customer]
from
(
Select V.LOB,V.[SAD Month][Demand Month],V.[SAD Quarter][Demand Quarter],V.[SAD Min Date][Min Date],V.Class,
[Item Type],[Offer PF],[LoB Region],[Key Account],Country,[Master Customer]
from OrderAggTable V
union
(
Select Z.LOB,Z.[RDD Month][Demand Month],Z.[RDD Quarter][Demand Quarter],Z.[RDD Min Date][Min Date],Z.Class,
[Item Type],[Offer PF],[LoB Region],[Key Account],Country,[Master Customer]
from OrderAggTable Z
)
union
(
Select LOB,[Demand Month],[Demand Quarter],[Min Date],Class[Class],[Item Type],[Offer PF],[LoB Region],
[Key Account],Country,[Master Customer] from ForecastAggTable
)
)A
cross join
(
select distinct [INDPOR Version],[INDPOR Timestamp]
from ForecastAggTable
)B
)D
where [Min Date]>=[INDPOR Timestamp]
)E
where ([SAD-OrderQty] + [RDD-OrderQty] + [Forecast Qty]<>0)
How about simplifying, and doing less passes of your tables.
In this example I do two scans of the forecast table, one for the distinct, and one for the union, and one scan of the orders table.
with cte as
(
select distinct [INDPOR Version],[INDPOR Timestamp]
from ForecastAggTable
)
,cte2 as
(
Select
V.LOB
,iif(DUP=0,V.[SAD Month] ,V.[RDD Month] ) [Demand Month]
,iif(DUP=0,V.[SAD Quarter] ,V.[RDD Quarter] ) [Demand Quarter]
,iif(DUP=0,V.[SAD Min Date] ,V.[RDD Min Date] ) [Min Date]
,V.[Book Date]
,V.Class
,V.[Item Type]
,V.[Offer PF]
,V.[LoB Region]
,V.[Key Account]
,V.Country
,V.[Master Customer]
,null [INDPOR Version]
,null [Forecast Qty]
,iif(DUP=0,v.[Order Qty] ,null ) [SAD-OrderQty]
,iif(DUP=0,V.[Order Revenue] ,null ) [SAD-OrderRevenue]
,iif(DUP=1,V.[Order Qty] ,null ) [RDD-OrderQty]
,iif(DUP=1,V.[Order Revenue] ,null ) [RDD-OrderRevenue]
from OrderAggTable V
cross join (select dup from (values (0),(1))a(dup)) a
union all
Select
LOB
,[Demand Month]
,[Demand Quarter]
,[Min Date]
,[Min Date]
,Class
,[Item Type]
,[Offer PF]
,[LoB Region]
,[Key Account]
,Country
,[Master Customer]
,[INDPOR Version]
,[Forecast Qty]
,null[SAD-OrderQty]
,null[SAD-OrderRevenue]
,null[RDD-OrderQty]
,null[RDD-OrderRevenue]
from ForecastAggTable
)
select
cte2.LOB
,cte.[INDPOR Version]
,cte.[INDPOR Timestamp]
,cte2.[Demand Month]
,cte2.[Demand Quarter]
,cte2.[Min Date]
,cte2.Class
,cte2.[Item Type]
,cte2.[Offer PF]
,cte2.[LoB Region]
,cte2.[Key Account]
,cte2.Country
,cte2.[Master Customer]
,isnull(sum(cte2.[Forecast Qty] ),0) [Forecast Qty]
,isnull(sum(cte2.[SAD-OrderQty] ),0) [SAD-OrderQty]
,isnull(sum(cte2.[SAD-OrderRevenue]) ,0) [SAD-OrderRevenue]
,isnull(sum(cte2.[RDD-OrderQty] ),0) [RDD-OrderQty]
,isnull(sum(cte2.[RDD-OrderRevenue]) ,0) [RDD-OrderRevenue]
from cte2
inner join cte
on cte2.[Book Date]>=cte.[INDPOR Timestamp]
where isnull(cte2.[INDPOR Version],cte.[INDPOR Version])=cte.[INDPOR Version]
group by
cte2.LOB
,cte2.[Demand Month]
,cte2.[Demand Quarter]
,cte2.[Min Date]
,cte2.Class
,cte2.[Item Type]
,cte2.[Offer PF]
,cte2.[LoB Region]
,cte2.[Key Account]
,cte2.Country
,cte2.[Master Customer]
,cte.[INDPOR Version]
,cte.[INDPOR Timestamp]
having
isnull(sum(cte2.[Forecast Qty] ),0) +
isnull(sum(cte2.[SAD-OrderQty] ),0) +
isnull(sum(cte2.[RDD-OrderQty] ),0)
!=0

Workaround for PIVOT statement

I have this query, is taking like 2 minutes to resolve, I need to find a workaround, I know that UNPIVOT has a better solution using CROSS APPLY, is there anything similar for PIVOT?
SELECT [RowId], [invoice date], [GL], [Entité], [001], [Loc], [Centre Cout], [Compte_1], [Interco_1], [Futur_1], [Department], [Division], [Compagnie], [Localisation], [Centre/Cout], [Compte], [Interco], [Futur], [Account], [Mobile], [Last Name], [First Name], [license fee], [GST], [HST], [PST], [Foreign Tax], [Sales Tax License], [Net Total], [Total], [ServiceType], [Oracle Cost Center], [CTRL], [EXPENSE], [Province]
FROM
(SELECT fd.[RowId], fc.[ColumnName], fd.[Value]
FROM dbo.FileData fd
INNER JOIN dbo.[FileColumn] fc
ON fc.[FileColumnId] = fd.[FileColumnId]
WHERE FileId = 1
AND TenantId = 1) x
PIVOT
(
MAX(Value)
FOR [ColumnName] IN ( [invoice date], [GL], [Entité], [001], [Loc], [Centre Cout], [Compte_1], [Interco_1], [Futur_1], [Department], [Division], [Compagnie], [Localisation], [Centre/Cout], [Compte], [Interco], [Futur], [Account], [Mobile], [Last Name], [First Name], [license fee], [GST], [HST], [PST], [Foreign Tax], [Sales Tax License], [Net Total], [Total], [ServiceType], [Oracle Cost Center], [CTRL], [EXPENSE], [Province])
) AS p
Pivots are great, but so are Conditional Aggregations. Also, there would be no datatype conficts or conversions necessary
SELECT [RowId]
,[invoice date] = max(case when [FileColumnId] = ??? then Value end)
,[GL] = max(case when [FileColumnId] = ??? then Value end)
,... more fields
FROM dbo.FileData fd
WHERE FileId = 1
AND TenantId = 1
Group By [RowId]
EDIT
You could add back the join to make it more readable.

Limiting results in SSRS SQL query

I am trying to build a report on our ticketing system using SSRS. I am bringing in fields from both an "incident body" table and an "incident details" table. What I am looking for is whether the ticket has slipped past an SLA for response to the customer.
I am checking for tickets past SLA two ways:
1) the ticket is past the SLA date and there is no detail record matching the predetermined types
2) the ticket has a detail record matching the predetermined types but it was after the SLA date
I was able to build the CTE section below but I am struggling with how to reduce the result of that to just the oldest matching row/record. A ticket should only show up once in the report.
For example:
Johnny Blogs updates a ticket using the CONTACTED_TM recordtype on 1/1/2016. The SLA was 12/31/2015. The next day (1/2/2016) he also emails the TM using the EMAILOUT recordtype. The CTE returns both these rows/records. I only want the first result.
My query code is below. I have tried using a SELECT TOP 1 in the CTE, but it just causes it to return no results.
WITH CTE (Date, [Action ID], Description, Note, [Login ID], [Seq.Group], [Incident #], ResponseDue) AS
(
SELECT Date, [Action ID], [Incident Details].Description, [Incident Details].Note, [Login ID], [Incident Details].[Seq.Group], [Incident Details].[Incident #], [Incident].[Due Date & Time:] as ResponseDue
FROM [_SMDBA_].[Incident Details]
JOIN [_SMDBA_].[Incident]
ON [Incident Details].[Incident #] = [Incident].[Incident #]
WHERE ([Action ID] = 'CONTACTED_TM' OR [Action ID] = 'TM_UNAVAILABLE' OR ([Action ID] = N'EMAILOUT' AND _SMDBA_.[Incident].[Client Email] in ([Email To Email From])))
--AND Date >= Incident.[Due Date & Time:]
)
SELECT
I.[Incident #]
,I.[Group Name]
,I.[Seq.Group] as IncidentGroupSeq
,I.[Due Date & Time:] as ResponseDue
,I.[Priority ID:]
,I.[Priority Duration]
,I.[Subject ID]
,I.[Open Date & Time] as OpenDate
,I.[Impact ID:] as Impact
,I.[Urgency ID:] as Urgency
,CTE.[Action ID]
,CTE.Description
,CTE.Note
,CTE.[Login ID]
,CTE.Date AS IncidentDetailsDate
,CTE.[Seq.Group] as DetailsGroupSeq
,_SMDBA_.CalcWorkingSeconds(1001,[Due Date & Time:],CTE.Date) as WorkingSecs
,CASE
WHEN CTE.date >= I.[Due Date & Time:] THEN 'Response was Late'
WHEN CTE.Date IS NULL THEN 'There was no response'
WHEN CTE.date <= I.[Due Date & Time:] THEN 'Met SLA'
WHEN I.[Due Date & Time:] IS NULL THEN 'No Response date set'
END AS SLAStatus
FROM [_SMDBA_].Incident I
LEFT OUTER JOIN CTE
ON CTE.[Incident #] = I.[Incident #]
WHERE
I.[Open Date & Time] >= #StartDate
AND I.[Open Date & Time] <= #EndDate
AND I.[Group Name] in (#Group)
AND I.[Impact ID:] in (#Impact)
AND I.[Urgency ID:] in (#Urgency)
AND I.[Opened Group:] = 'SERVICE DESK'
Something like this, as referenced in the comments.
WITH CTE ([Date], [Action ID], Description, Note, [Login ID], [Seq.Group], [Incident #], ResponseDue) AS
(
SELECT
[Date],
[Action ID],
[Incident Details].Description,
[Incident Details].Note,
[Login ID],
[Incident Details].[Seq.Group],
[Incident Details].[Incident #],
[Incident].[Due Date & Time:] as ResponseDue,
row_number() over (partition by [Incident Details].[Incident #] order by [Date] desc) as RN
FROM [_SMDBA_].[Incident Details]
JOIN
[_SMDBA_].[Incident]
ON [Incident Details].[Incident #] = [Incident].[Incident #]
WHERE
([Action ID] = 'CONTACTED_TM' OR [Action ID] = 'TM_UNAVAILABLE' OR
([Action ID] = N'EMAILOUT' AND _SMDBA_.[Incident].[Client Email] in ([Email To Email From])))
--AND Date >= Incident.[Due Date & Time:]
)
SELECT
I.[Incident #]
,I.[Group Name]
,I.[Seq.Group] as IncidentGroupSeq
,I.[Due Date & Time:] as ResponseDue
,I.[Priority ID:]
,I.[Priority Duration]
,I.[Subject ID]
,I.[Open Date & Time] as OpenDate
,I.[Impact ID:] as Impact
,I.[Urgency ID:] as Urgency
,CTE.[Action ID]
,CTE.Description
,CTE.Note
,CTE.[Login ID]
,CTE.Date AS IncidentDetailsDate
,CTE.[Seq.Group] as DetailsGroupSeq
,_SMDBA_.CalcWorkingSeconds(1001,[Due Date & Time:],CTE.Date) as WorkingSecs
,CASE
WHEN CTE.date >= I.[Due Date & Time:] THEN 'Response was Late'
WHEN CTE.Date IS NULL THEN 'There was no response'
WHEN CTE.date <= I.[Due Date & Time:] THEN 'Met SLA'
WHEN I.[Due Date & Time:] IS NULL THEN 'No Response date set'
END AS SLAStatus
FROM [_SMDBA_].Incident I
LEFT OUTER JOIN CTE
ON CTE.[Incident #] = I.[Incident #]
WHERE
I.[Open Date & Time] >= #StartDate
AND I.[Open Date & Time] <= #EndDate
AND I.[Group Name] in (#Group)
AND I.[Impact ID:] in (#Impact)
AND I.[Urgency ID:] in (#Urgency)
AND I.[Opened Group:] = 'SERVICE DESK'
AND CTE.RN = 1

T-SQL [UNION ALL] removing records from query result

Have a simple UNION ALL query marrying the results of two queries. The first query, run independently, returns 1208 records and the second 14. I would expect a properly syntaxed UNION ALL to return 1222 records but mine falls to 896.
Makes zero sense to me:
SELECT a.WBS_ELEMENT_ID as [WBS Element],
a.WBS_ELEMENT_DESC as [WBS Element Desc],
a.UHC_INDUSTRY as [Industry],
a.UHC_SECTOR as [Sector],
a.UHC_DUNS_NUMBER as [UHC DUNS Number],
a.UHC_DUNS_NAME as [UHC DUNS Name],
a.PRIORITY_SUB_SECTOR as [Priority Sub Sector],
a.BUDGET_ALLOCATION as [Budget Allocation],
a.LAST_UPDATED_ON as [Last Updated]
FROM DimSectorPd a
WHERE a.wbs_element_id is not null
UNION ALL
SELECT ROW_NUMBER() OVER (ORDER BY a.wbs_element_desc) as [WBS Element],
a.WBS_ELEMENT_DESC as [WBS Element name],
a.UHC_INDUSTRY as [Industry],
a.UHC_SECTOR as [Sector],
a.UHC_DUNS_NUMBER as [UHC DUNS Number],
a.UHC_DUNS_NAME as [UHC DUNS Name],
a.PRIORITY_SUB_SECTOR as [Priority Sub Sector],
a.BUDGET_ALLOCATION as [Budget Allocation],
a.LAST_UPDATED_ON as [Last Updated]
from dimsectorpd a where a.WBS_ELEMENT_ID is null
Your queries should return all rows in the table. Unless the table changes between executions, the results from running the subqueries separately should be the same as from running them with the UNION ALL.
As a note, if you want to simplify the query, then you can do:
SELECT COALESCE(a.WBS_ELEMENT_ID,
ROW_NUMBER() OVER (PARTITION BY wbs_element_id ORDER BY a. wbs_element_desc)
) as [WBS Element],
a.WBS_ELEMENT_DESC as [WBS Element Desc],
a.UHC_INDUSTRY as [Industry],
a.UHC_SECTOR as [Sector],
a.UHC_DUNS_NUMBER as [UHC DUNS Number],
a.UHC_DUNS_NAME as [UHC DUNS Name],
a.PRIORITY_SUB_SECTOR as [Priority Sub Sector],
a.BUDGET_ALLOCATION as [Budget Allocation],
a.LAST_UPDATED_ON as [Last Updated]
FROM DimSectorPd a;
Obviously there is nothing wrong with your syntax, but if you want to try a different approach to getting your UNION ALL to work with ROW_NUMBER. Here it is:
;WITH q1
AS (
SELECT a.WBS_ELEMENT_ID AS [WBS Element]
,a.WBS_ELEMENT_DESC AS [WBS Element Desc]
,a.UHC_INDUSTRY AS [Industry]
,a.UHC_SECTOR AS [Sector]
,a.UHC_DUNS_NUMBER AS [UHC DUNS Number]
,a.UHC_DUNS_NAME AS [UHC DUNS Name]
,a.PRIORITY_SUB_SECTOR AS [Priority Sub Sector]
,a.BUDGET_ALLOCATION AS [Budget Allocation]
,a.LAST_UPDATED_ON AS [Last Updated]
FROM DimSectorPd a
WHERE a.wbs_element_id IS NOT NULL
UNION ALL
SELECT b.WBS_ELEMENT_ID AS [WBS Element] --just bring NULL values
,b.WBS_ELEMENT_DESC AS [WBS Element name]
,b.UHC_INDUSTRY AS [Industry]
,b.UHC_SECTOR AS [Sector]
,b.UHC_DUNS_NUMBER AS [UHC DUNS Number]
,b.UHC_DUNS_NAME AS [UHC DUNS Name]
,b.PRIORITY_SUB_SECTOR AS [Priority Sub Sector]
,b.BUDGET_ALLOCATION AS [Budget Allocation]
,b.LAST_UPDATED_ON AS [Last Updated]
FROM dimsectorpd b
WHERE b.WBS_ELEMENT_ID IS NULL
)
SELECT CASE
WHEN q1.[WBS Element] IS NULL
THEN ROW_NUMBER() OVER (ORDER BY q1.WBS_Element_Desc)
ELSE q1.[WBS Element]
END [WBS_Element]
,q1.[WBS Element Desc]
,q1.Industry
,q1.Sector
,q1.[UHC DUNS Number]
,q1.[UHC DUNS Name]
,q1.[Priority Sub Sector]
,q1.[Budget Allocation]
,q1.[Last Updated]
FROM q1
Here is a simplified example can you see if it works on your server?
SELECT a.low AS [My ID],
a.name AS [My Letter]
FROM master..spt_values as a
WHERE low is not null
UNION ALL
SELECT ROW_NUMBER() OVER (ORDER BY a.name) AS [My ID],
a.name AS [My Letter]
FROM master..spt_values as a
WHERE a.low is null
master..spt_values as 2515 rows on my system...