Query the size of all tables in Synapse Analytics - azure-synapse

I want to be able to query and filter tables based on it's size
I already know sp_spaceused, but it shows the size for one table at a time

Here's that view adjusted to use sys.pdw_permanent_table_mappings as per the Synapse recommendation
SELECT two_part_name, SUM( row_count ) AS row_count, SUM( reserved_space_GB ) AS reserved_space_GB
FROM dbo.vTableSizes
GROUP BY two_part_name
ORDER BY reserved_space_GB DESC;
The view:
ALTER VIEW dbo.vTableSizes
AS
WITH base
AS
(
SELECT
GETDATE() AS [execution_time]
, DB_NAME() AS [database_name]
, s.name AS [schema_name]
, t.name AS [table_name]
, QUOTENAME(s.name)+'.'+QUOTENAME(t.name) AS [two_part_name]
, nt.[name] AS [node_table_name]
, ROW_NUMBER() OVER(PARTITION BY nt.[name] ORDER BY (SELECT NULL)) AS [node_table_name_seq]
, tp.[distribution_policy_desc] AS [distribution_policy_name]
, c.[name] AS [distribution_column]
, nt.[distribution_id] AS [distribution_id]
, i.[type] AS [index_type]
, i.[type_desc] AS [index_type_desc]
, nt.[pdw_node_id] AS [pdw_node_id]
, pn.[type] AS [pdw_node_type]
, pn.[name] AS [pdw_node_name]
, di.name AS [dist_name]
, di.position AS [dist_position]
, nps.[partition_number] AS [partition_nmbr]
, nps.[reserved_page_count] AS [reserved_space_page_count]
, nps.[reserved_page_count] - nps.[used_page_count] AS [unused_space_page_count]
, nps.[in_row_data_page_count]
+ nps.[row_overflow_used_page_count]
+ nps.[lob_used_page_count] AS [data_space_page_count]
, nps.[reserved_page_count]
- (nps.[reserved_page_count] - nps.[used_page_count])
- ([in_row_data_page_count]
+ [row_overflow_used_page_count]+[lob_used_page_count]) AS [index_space_page_count]
, nps.[row_count] AS [row_count]
from
sys.schemas s
INNER JOIN sys.tables t
ON s.[schema_id] = t.[schema_id]
INNER JOIN sys.indexes i
ON t.[object_id] = i.[object_id]
AND i.[index_id] <= 1
INNER JOIN sys.pdw_table_distribution_properties tp
ON t.[object_id] = tp.[object_id]
INNER JOIN sys.pdw_permanent_table_mappings tm
ON t.[object_id] = tm.[object_id]
INNER JOIN sys.pdw_nodes_tables nt
ON tm.[physical_name] = nt.[name]
INNER JOIN sys.dm_pdw_nodes pn
ON nt.[pdw_node_id] = pn.[pdw_node_id]
INNER JOIN sys.pdw_distributions di
ON nt.[distribution_id] = di.[distribution_id]
INNER JOIN sys.dm_pdw_nodes_db_partition_stats nps
ON nt.[object_id] = nps.[object_id]
AND nt.[pdw_node_id] = nps.[pdw_node_id]
AND nt.[distribution_id] = nps.[distribution_id]
LEFT OUTER JOIN (select * from sys.pdw_column_distribution_properties where distribution_ordinal = 1) cdp
ON t.[object_id] = cdp.[object_id]
LEFT OUTER JOIN sys.columns c
ON cdp.[object_id] = c.[object_id]
AND cdp.[column_id] = c.[column_id]
WHERE pn.[type] = 'COMPUTE'
)
, size
AS
(
SELECT
[execution_time]
, [database_name]
, [schema_name]
, [table_name]
, [two_part_name]
, [node_table_name]
, [node_table_name_seq]
, [distribution_policy_name]
, [distribution_column]
, [distribution_id]
, [index_type]
, [index_type_desc]
, [pdw_node_id]
, [pdw_node_type]
, [pdw_node_name]
, [dist_name]
, [dist_position]
, [partition_nmbr]
, [reserved_space_page_count]
, [unused_space_page_count]
, [data_space_page_count]
, [index_space_page_count]
, [row_count]
, ([reserved_space_page_count] * 8.0) AS [reserved_space_KB]
, ([reserved_space_page_count] * 8.0)/1000 AS [reserved_space_MB]
, ([reserved_space_page_count] * 8.0)/1000000 AS [reserved_space_GB]
, ([reserved_space_page_count] * 8.0)/1000000000 AS [reserved_space_TB]
, ([unused_space_page_count] * 8.0) AS [unused_space_KB]
, ([unused_space_page_count] * 8.0)/1000 AS [unused_space_MB]
, ([unused_space_page_count] * 8.0)/1000000 AS [unused_space_GB]
, ([unused_space_page_count] * 8.0)/1000000000 AS [unused_space_TB]
, ([data_space_page_count] * 8.0) AS [data_space_KB]
, ([data_space_page_count] * 8.0)/1000 AS [data_space_MB]
, ([data_space_page_count] * 8.0)/1000000 AS [data_space_GB]
, ([data_space_page_count] * 8.0)/1000000000 AS [data_space_TB]
, ([index_space_page_count] * 8.0) AS [index_space_KB]
, ([index_space_page_count] * 8.0)/1000 AS [index_space_MB]
, ([index_space_page_count] * 8.0)/1000000 AS [index_space_GB]
, ([index_space_page_count] * 8.0)/1000000000 AS [index_space_TB]
FROM base
)
SELECT *
FROM size
;

The documented DMV queries allow you to get a report of all table sizes.

Related

How to insert numerous rows on a table from another table with conditions on Oracle SQL

I do have a problem on how to insert numerous rows of data into a table from an existing table with conditions. So this first code is how I created my table.
CREATE TABLE MARKETING_COMMODITY
AS(
SELECT A.DTIME_SIGNATURE
, A.AMT_SIGNED
, A.CNT_SIGNED
, A.APPLICATION_AMOUNT
, A.PRODUCT
, A.PRODUCT_TYPE
, A.PRODUCT_PRICE
, VSR.NAME_PRODUCER
, vsr.text_model_number
, vsp.partner_name
, vsp.partner_brand
, vspl.salesroom
, vspl.mall
FROM DM_SALES.V_SALES_DM_DATA A
LEFT JOIN DM_SALES.V_SALES_DM_PARTNER VSP ON A.CODE_SALESROOM_PARTNER = VSP.CODE_SALESROOM_PARTNER
LEFT JOIN dm_sales.v_sales_dm_pos_list vspl on a.code_salesroom = vspl.code_salesroom
LEFT JOIN DM_SALES.V_SALES_DM_CONTRACT_BUNDLE VSR ON A.CONTRACT_NUMBER = VSR.CONTRACT_NUMBER
WHERE 1=1
AND a.contract_state <> 'Cancelled'
AND a.cnt_signed=1
AND A.LOAN_TYPE = 'Consumer Loan'
AND (TRUNC(A.DTIME_SIGNATURE) BETWEEN DATE'2022-01-01' AND DATE'2022-08-31')
;
And this is how I'd like to insert my new rows (its like updating the table to get the new data up to the current day)
INSERT INTO MARKETING_COMMODITY
VALUES(
SELECT A.DTIME_SIGNATURE
, A.AMT_SIGNED
, A.CNT_SIGNED
, A.APPLICATION_AMOUNT
, A.PRODUCT
, A.PRODUCT_TYPE
, A.PRODUCT_PRICE
, VSR.NAME_PRODUCER
, vsr.text_model_number
, vsp.partner_name
, vsp.partner_brand
, vspl.salesroom
, vspl.mall
FROM DM_SALES.V_SALES_DM_DATA A
LEFT JOIN DM_SALES.V_SALES_DM_PARTNER VSP ON A.CODE_SALESROOM_PARTNER = VSP.CODE_SALESROOM_PARTNER
LEFT JOIN dm_sales.v_sales_dm_pos_list vspl on a.code_salesroom = vspl.code_salesroom
LEFT JOIN DM_SALES.V_SALES_DM_CONTRACT_BUNDLE VSR ON A.CONTRACT_NUMBER = VSR.CONTRACT_NUMBER
WHERE 1=1
AND a.contract_state <> 'Cancelled'
AND a.cnt_signed=1
AND A.LOAN_TYPE = 'Consumer Loan'
AND (TRUNC(A.DTIME_SIGNATURE) BETWEEN DATE'2022-09-01' AND DATE'2022-09-10')
;
What can you suggest? Thanks!
Don't confuse the syntax for "CREATE TABLE AS SELECT" with the syntax for "INSERT INTO SELECT". Explicitely add the columns you're inserting into and remove the "AS" keyword. This should work:
INSERT INTO MARKETING_COMMODITY
(
dtime_signature
,amt_signed
,cnt_signed
,application_amount
,product
,product_type
,product_price
,name_producer
,text_model_number
,partner_name
,partner_brand
,salesroom
,mall
)
SELECT A.DTIME_SIGNATURE
, A.AMT_SIGNED
, A.CNT_SIGNED
, A.APPLICATION_AMOUNT
, A.PRODUCT
, A.PRODUCT_TYPE
, A.PRODUCT_PRICE
, VSR.NAME_PRODUCER
, vsr.text_model_number
, vsp.partner_name
, vsp.partner_brand
, vspl.salesroom
, vspl.mall
FROM DM_SALES.V_SALES_DM_DATA A
LEFT JOIN DM_SALES.V_SALES_DM_PARTNER VSP ON A.CODE_SALESROOM_PARTNER = VSP.CODE_SALESROOM_PARTNER
LEFT JOIN dm_sales.v_sales_dm_pos_list vspl on a.code_salesroom = vspl.code_salesroom
LEFT JOIN DM_SALES.V_SALES_DM_CONTRACT_BUNDLE VSR ON A.CONTRACT_NUMBER = VSR.CONTRACT_NUMBER
WHERE 1=1
AND a.contract_state <> 'Cancelled'
AND a.cnt_signed=1
AND A.LOAN_TYPE = 'Consumer Loan'
AND (TRUNC(A.DTIME_SIGNATURE) BETWEEN DATE'2022-09-01' AND DATE'2022-09-10')
;

Substitute the Lag() function with another similiar option in Sybase

With the help of some of the users here in stackoverflow, I reached to the following query. The problem is that this query works well in SQL Server, but not in Sybase as it doesn't support LAG(). I have been trying to get it to work but no success.
The query is quite complicated but help in subsituting the LAG() function with something similar would be appreciated.
SELECT created
, bname
, total_share
FROM (
SELECT TT.created
, TT.bname
, TT.total_share
, lag(TT.total_share) OVER (
PARTITION BY TT.bname ORDER BY TT.created
) AS prev_share
FROM (
SELECT DISTINCT t.created AS created
, t.NAME AS bname
, t.total_share
FROM (
SELECT cast(fsp.created AS VARCHAR(19)) AS created
, e.NAME
, e.initials
, fsp.modified
, CASE
WHEN cl.price_per_item = 0
THEN CAST('' AS DECIMAL(18, 2))
ELSE CAST((fsp.new_price / cl.price_per_item * 100) AS DECIMAL(18, 2))
END AS new_share
, CASE
WHEN cl.price_per_item = 0
THEN CAST('' AS DECIMAL(18, 2))
ELSE CAST((prev / cl.price_per_item * 100) AS DECIMAL(18, 2))
END AS old_share
, fs.STATE
, CASE
WHEN fsp.prev_price IS NULL
THEN 0
ELSE fsp.prev_price
END AS prev
, fsp.new_price AS nprice
, (prev - nprice) AS diff
, new_share - old_share AS diff_share
, old_share + diff_share AS total_share
FROM project_manager pm
INNER JOIN dba.project p ON pm.project = p.id
LEFT JOIN dba.contract c ON p.id = c.project
LEFT JOIN dba.contract_line cl ON cl.contract = c.id
LEFT JOIN dba.product pt ON cl.product = pt.id
LEFT JOIN dba.specified_product sp ON sp.product = pt.id
LEFT JOIN dba.frozen_sale fs ON fs.spec_product = sp.id
AND fs.contract = c.id
AND fs.line = cl.idx
LEFT JOIN dba.frozen_sale_split fsp ON fsp.frozen_sale = fs.id
AND fsp.employee = pm.consultant
LEFT JOIN dba.employee e ON fsp.employee = e.person
LEFT JOIN dba.person ps ON fsp.creator = ps.id
WHERE p.id = 50000002735
AND e.NAME IS NOT NULL
) AS t
) TT /* here */
) x
WHERE (
prev_share IS NULL
OR prev_share total_share
)
ORDER BY created
, bname
The following code is untested, but the approach is to use the row_number window function to assign a sequential number (rnum in the code) to each row, ordered by the created value. This is done in the initial CTE. The main query then joins that CTE to itself, with a join condition of a difference of one in the rnum values.
with inp as (
SELECT TT.created
, TT.bname
, TT.total_share
, row_number over(order by TT.created) as rnum
FROM (
SELECT DISTINCT t.created AS created
, t.NAME AS bname
, t.total_share
FROM (
SELECT cast(fsp.created AS VARCHAR(19)) AS created
, e.NAME
, e.initials
, fsp.modified
, CASE
WHEN cl.price_per_item = 0
THEN CAST('' AS DECIMAL(18, 2))
ELSE CAST((fsp.new_price / cl.price_per_item * 100) AS DECIMAL(18, 2))
END AS new_share
, CASE
WHEN cl.price_per_item = 0
THEN CAST('' AS DECIMAL(18, 2))
ELSE CAST((prev / cl.price_per_item * 100) AS DECIMAL(18, 2))
END AS old_share
, fs.STATE
, CASE
WHEN fsp.prev_price IS NULL
THEN 0
ELSE fsp.prev_price
END AS prev
, fsp.new_price AS nprice
, (prev - nprice) AS diff
, new_share - old_share AS diff_share
, old_share + diff_share AS total_share
FROM project_manager pm
INNER JOIN dba.project p ON pm.project = p.id
LEFT JOIN dba.contract c ON p.id = c.project
LEFT JOIN dba.contract_line cl ON cl.contract = c.id
LEFT JOIN dba.product pt ON cl.product = pt.id
LEFT JOIN dba.specified_product sp ON sp.product = pt.id
LEFT JOIN dba.frozen_sale fs ON fs.spec_product = sp.id
AND fs.contract = c.id
AND fs.line = cl.idx
LEFT JOIN dba.frozen_sale_split fsp ON fsp.frozen_sale = fs.id
AND fsp.employee = pm.consultant
LEFT JOIN dba.employee e ON fsp.employee = e.person
LEFT JOIN dba.person ps ON fsp.creator = ps.id
WHERE p.id = 50000002735
AND e.NAME IS NOT NULL
) AS t
) TT
)
SELECT
created
, bname
, total_share
, prev.total_share as prev_share
FROM
inp
left join inp as prev on prev.rnum=inp.rnum-1
and prev.bname=inp.bname
WHERE (
prev.total_share IS NULL
OR prev.total_share total_share
)
ORDER BY
created
, bname

Issues with join statement not displaying records

I'm trying to accomplish the following: Display all rows for Mgt.Dbo.Tab1 (157 rows) while joining 3 tables. The query only provides results for 76 rows from Mgt. i've tried using left join to no avail. HELP! TIA
Code:
select
mgt.UID
, Mgt.emp_num
, emp.EMP_NAME
, RTRIM(mgt.COMPANY)
, 'Company 1'
, jnl.d_w
, mgt.d_r
, jnl.UNITS
, jnl.RATE
, mgt.hours
, mgt.RATE
, rtrim(jnl.MEMO)
, mgt.UNIQUE_ID
, jnl.grow
, jnl.grow_num
, hdr.ch_date
, mgt.sub_by
, hdr.ch_num
from Mgt.dbo.sick as mgt
inner join Comp1.DBO.emp as emp
on Mgt.emp_num = emp.emp_num
inner join Comp1.dbo.hdr as hdr
on Mgt.emp_num = hdr.emp_num
inner join Comp1.dbo.jnl as jnl
on jnl.c_n = hdr.c_n
where COMPANY in ('Test')
and jnl.wg = 'SP'
and mgt.d_r = jnl.d_w
and mgt.d_r >= '8/20/2017'
and mgt.d_r <= '9/1/2017'
and mgt.d_r=jnl.d_w
After your edit, swap your inner joins for left joins and move any where clauses on left joined tables to the join condition:
select
mgt.UID
, mgt.emp_num
, emp.EMP_NAME
, RTRIM(mgt.COMPANY)
, 'Company 1'
, jnl.d_w
, mgt.d_r
, jnl.UNITS
, jnl.RATE
, mgt.hours
, mgt.RATE
, rtrim(jnl.MEMO)
, mgt.UNIQUE_ID
, jnl.grow
, jnl.grow_num
, hdr.ch_date
, mgt.sub_by
, hdr.ch_num
from Mgt.dbo.sick as mgt
left join Comp1.DBO.emp as emp
on Mgt.emp_num = emp.emp_num
left join Comp1.dbo.hdr as hdr
on Mgt.emp_num = hdr.emp_num
left join Comp1.dbo.jnl as jnl
on jnl.c_n = hdr.c_n
and jnl.wg = 'SP'
and jnl.d_w = mgt.d_r
where mgt.COMPANY in ('Test')
and mgt.d_r >= '8/20/2017'
and mgt.d_r <= '9/1/2017'
it appears the following did the trick:
select
mgt.UID
, mgt.emp_num
, emp.EMP_NAME
, RTRIM(mgt.COMPANY)
, 'Company 1'
, jnl.d_w
, mgt.d_r
, jnl.UNITS
, jnl.RATE
, mgt.hours
, mgt.RATE
, rtrim(jnl.MEMO)
, mgt.UNIQUE_ID
, jnl.grow
, jnl.grow_num
, hdr.ch_date
, mgt.sub_by
, hdr.ch_num
from Mgt.dbo.sick as mgt
left join Comp1.DBO.jnl as jnl
inner join comp1.dbo.hdr as hdr
on jnl.c_n= hdr.c_n
on jnl.d_w=mgt.d_r
and mgt.unique_id=jnl.memo
and hdr.emp_num=mgt.emp_num
where mgt.COMPANY in ('Test')
and mgt.d_r >= '8/20/2017'
and mgt.d_r <= '9/1/2017'
I was missing an inner join.

This SQL query is taking too long

This SQL query is taking too long
SELECT
s.State
, ServiceCenter
, s.LocationId
, LMG.dbo.ProperCase(LastName + ', ' + FirstName + ' (' + convert(varchar,s.ClientId) + ')') as Client
, ISNULL(ul.ContractorName, ServiceCenter) as ContractorName
, InvoiceId as InvoiceNumber
, s.ItemDescription
, s.Quantity
--, s.Revenue
--, SUM(s.Quantity) as Quantity
, SUM(s.Quantity * s.UnitPrice) as Revenue
--, SUM(s.Quantity * s.Revenue) as Total
, SUM(Quantity * lxref.Amount) as ContractorPayment
, (SELECT InvoiceAmount FROM AG1.MAMOZI.dbo.tInvoices i WHERE s.InvoiceId = i.invoiceId AND DeletedStatus IS NULL) as InvoiceAmount
, (SELECT SUM(Payment) FROM AG1.MAMOZI.dbo.tPayments p WHERE s.InvoiceId = p.invoiceId AND DeletedStatus IS NULL) as PaymentAmount
, (SELECT PaymentType FROM #PaymentTypeGuardian pt WHERE pt.ClientId = s.ClientId AND pt.InvoiceId = s.InvoiceId) as PaymentType
, ISNULL((SELECT SUM(AccountBalance) FROM [PLUSREPORT].Warehouse_LMG1.dbo.RptAccountBalance a WHERE a.CompanyId = 3 AND a.ClientId = CAST(s.ClientId as varchar(max))), 0) as AccountBalance
FROM #ServicePaymentGuardian s
INNER JOIN AG1.MAMOZI.dbo.tClient c on s.ClientId = c.ClientId
INNER JOIN DATABASESAVE.MAMO.org.LocationExtended le on s.LocationID = le.OrgDatabaseid
INNER JOIN DATABASESAVE.MAMO.jur.Location ul on le.LocationId = ul.LocationId AND ul.LocationTypeid = 2
INNER JOIN DATABASESAVE.MAMO.base.Jurisdiction uj on ul.JurisdictionId = uj.JurisdictionId AND uj.CompanyId = 3
INNER JOIN DATABASESAVE.MAMO.jur.LocationServicePaymentXref lxref on ul.LocationId = lxref.LocationId and s.ServicePaymentId = lxref.ServicePaymentId
GROUP BY
s.State
, ServiceCenter
, s.LocationId
, s.ClientId
, c.LastName
, c.FirstName
, s.InvoiceId
, s.Quantity
, s.ItemDescription
, s.ServicePaymentId
, ul.ContractorName
Order by State, ServiceCenter, InvoiceNumber, LastName, FirstName, ItemDescription
see execution plan - maybe you need to add indexes
run query without sub-queries and see how long it will take then
try to split query to smaller parts (and run it separately) to find out which part slows query down

Applying cluster indexing to a view in SQL Server 2012

I have a view which queries around 1+ million rows and takes around 10-15 minutes to finish its execution,I want to provide cluster indexing to it so that it exists in physical schema and takes less time to load, but there are a number of constraints in order to provide cluster indexing i.e. only INNER JOIN are allowed and No subqueries should be present in views defination how do I replace the LEFT JOIN present in this view with INNER JOIN and how do I eliminate subqueries from this views defination so that cluster indexing can be applied to it.
CREATE view [dbo].[FTM_ProfileDetailsView] with SCHEMABINDING as
select FTM.Id
, FTM.EmployeeId
, FTM.CustomerId
, FTM.AbsenceFirstDate
, FTM.BackgroundHistory
, FTM.BackgroundHistoryComments
, FTM.IsEmployeeAbsent,FTM.ServiceId
, Case When isnull(FTM.IsSelfManagement,'')='' THEN cast(0 as bit) ELSE FTM.IsSelfManagement END as IsSelfManagement
, PR.ServiceLineId,FTM.ProfileId,PR.StatusId,Status.Status as StatusName
, PR.ReasonID
, PR.ModifiedDate
, PR.WithdrawnReason
, PR.CreatedBy
, PR.CreatedDate
, PR.IsActive
, mgrs.usernames as LineManagers
, cust.CustomerName
, ltrim(rtrim( emp.EmployeeTitle+' '+ emp.FirstName+' '+ emp.Surname)) as EmployeeFullName
, FTM.ProfileManagerId
, FTM.IsProfileManagement
, AM.MonitoringChecks
, AM.Frequency
, AM.ProfileManagerNotes
, AM.TaskDateAndTime
, FTM.ProfileManagementCriteriaId
,cast(case when PR.StatusId = 13 then 1 else 0 end as bit) as IsActiveMonitoring
, CustServ.CustomerServiceName
, BU.Name as BusinessUnit
, emp.DASID
, emp.DateOfBirth as EmployeeDOB
, addr.PostCode
, coninfo.Email
, (select top 1
StatusId from dbo.PR_Profileintervention ProfileInt
where ProfileInt.ProfileId=FTM.Profileid
order by ProfileInt.Id desc) as LatestInterventionStatusId
, (select name from dbo.FTM_Intervention Intr
where Intr.Id=(select top 1 InterventionId from dbo.PR_Profileintervention ProfileInt
where ProfileInt.ProfileId=FTM.Profileid
order by ProfileInt.Id desc))
as LatestInterventionName from FTM_Profile FTM
LEFT JOIN dbo.ProfileManagersView mgrs ON mgrs.ProfileID = FTM.ProfileID
INNER JOIN dbo.Customer cust on cust.Id= FTM.CustomerId
INNER JOIN dbo.Employee emp on emp.Id = FTM.EmployeeId
INNER JOIN dbo.PR_Profile PR on PR.Profileid=FTM.ProfileId
LEFT JOIN dbo.BusinessUnit BU on BU.Id=PR.BUId
LEFT JOIN dbo.PR_dv_Status [Status] on [Status].Id = PR.StatusId
LEFT JOIN dbo.CM_ActiveMonitoringDetails AM on AM.ProfileId = PR.Profileid
LEFT JOIN dbo.FTM_CustomerServiceMapping CustServ on CustServ.ServiceId = FTM.ServiceId and CustServ.CustomerId = FTM.CustomerId
LEFT JOIN dbo.contact con on con.Id = emp.ContactID
LEFT JOIN dbo.address addr on addr.Id = con.HomeAddressId
LEFT JOIN dbo.contactinfo coninfo on coninfo.Id = con.ContactInfoId
I have a suggestion. Can you try and change your query so the sub -queries in the SELECT are placed in CROSS APPLYs?
So something along the lines of this in your WHERE clause:
CROSS APPLY (
select top 1 StatusId AS LatestInterventionStatusId
from dbo.PR_Profileintervention ProfileInt
where ProfileInt.ProfileId=FTM.Profileid
order by ProfileInt.Id desc
) LatestInterventionStatusId
CROSS APPLY (
select name AS LatestInterventionName
from dbo.FTM_Intervention Intr
where Intr.Id=(select top 1 InterventionId
from dbo.PR_Profileintervention ProfileInt
where ProfileInt.ProfileId=FTM.Profileid
order by ProfileInt.Id desc)
)LatestInterventionName
And then of course change the column names in the SELECT to something like this:
, LatestInterventionStatusId.LatestInterventionStatusId
, LatestInterventionName.LatestInterventionName
Give this a go and let me know if it makes a different.
Ok, you didn't give me an answer on my question, but the subqueries should be changed. Try to use this instead the two subqueries:
/*
...
, emp.DateOfBirth as EmployeeDOB
, addr.PostCode
, coninfo.Email
*/
, p.StatusId as LatestInterventionStatusId
, p.name as LatestInterventionName
from FTM_Profile FTM
OUTER APPLY (
select TOP 1 Intr.name, ProfileInt.StatusId
from dbo.PR_Profileintervention ProfileInt
LEFT JOIN dbo.FTM_Intervention Intr ON Intr.Id = ProfileInt.InterventionId
where ProfileInt.ProfileId = FTM.Profileid
order by ProfileInt.Id desc
) p
/*
LEFT JOIN dbo.ProfileManagersView mgrs ON mgrs.ProfileID = FTM.ProfileID
INNER JOIN dbo.Customer cust on cust.Id= FTM.CustomerId
INNER JOIN dbo.Employee emp on emp.Id = FTM.EmployeeId
...
*/