T SQL how to add extra elements in xml - sql

Hi im trying to generate xml from my t sql query. But im having problems with adding extra elements in my xml. Or is it even possible to do that. my sql query is like this.
SELECT
m.DeviceId as IndividualItemNo,
Name = 'B',
w.BTime as Value,
CAST(CONVERT(VARCHAR(8), w.EndTS, 112) AS INT) AS [Date],
CONVERT(VARCHAR(5), w.EndTS,108) + '+0000' AS [Time],
g.GroupName
FROM Machine m
INNER JOIN [Group] g ON m.GroupId = g.GroupId
INNER JOIN [EDWCompany] e ON g.CompanyKey = e.CompanyKey
LEFT JOIN WorkingPass w ON m.MachineId = w.MachineId and w.WorkingPassId = (SELECT MAX(w.WorkingPassId) FROM WorkingPass w WHERE MachineId = m.MachineId )
WHERE g.CompanyKey = 105
GROUP BY m.DeviceId, w.EndTS , w.BTime , g.GroupName, e.CompanyNo, m.MachineId
ORDER BY m.DeviceId
FOR XML PATH ('IndividualItem'), ROOT ('IndividualItem_Report'), ELEMENTS
My XML result:
<IndividualItem_Report>
<IndividualItem>
<IndividualItemNo>027FDF3014953</IndividualItemNo>
<Name>B</Name>
<Value>3535</Value>
<Date>20130221</Date>
<Time>10:32+0000</Time>
<GroupName>TARKETT AB</GroupName>
</IndividualItem>
</IndividualItem_Report>
But i want to add extra elements. So this is what i want.
<IndividualItem_Report>
<IndividualItem>
<IndividualItemNo>027FDF3014953</IndividualItemNo>
<HourMeterList>
<HourMeter>
<Name>B</Name>
<Value>3535</Value>
<Date>20130221</Date>
<Time>10:32+0000</Time>
<GroupName>TARKETT AB</GroupName>
</HourMeter>
</HourMeterList>
</IndividualItem>
</IndividualItem_Report>

I assume HourMeterList is a multi value
From working code
This is just part of the select list
,(select top 1 'MV'
from docMVenum1 with (nolock)
where docMVenum1.sID = docSVsys.sID and docMVenum1.enumID = '179')
as 'RFPResponse/#SVMV'
,(select top 1 'RFP Response#'
from docMVenum1 with (nolock)
where docMVenum1.sID = docSVsys.sID and docMVenum1.enumID = '179')
as 'RFPResponse/#displayName'
, (select docEnum1.value
from docMVenum1 with (nolock)
join docEnum1 with (nolock)
on docEnum1.enumID = docMVenum1.enumID and docEnum1.valueID = docMVenum1.valueID
where docMVenum1.sID = docSVsys.sID and docMVenum1.enumID = '179'
order by docEnum1.value
FOR XML PATH (''), type
) as [RFPResponse]
Sample output
<RFPResponse SVMV="MV" displayName="RFP Response#">
<value>RFPa</value>
<value>RFPb</value>
</RFPResponse>

Related

Rownumber is not working as expected in report builder?

So I have a report that used this prod from sql like so:
alter PROCEDURE [dbo].[PHA00B01801_VN_BCThuocdakedontheoyeucau]
--declare
#TUNGAY DATETIME = '20220202',
#DENNGAY DATETIME = '20220204',
#KHODUOC_ID int = null,
#TENBACSI nvarchar(max) = null,
#MABENHVIEN VARCHAR(10)
AS
set #TENBACSI = ISNULL(#TENBACSI, '')
select st.TENBACSI, st.SOTOATHUOC, st.TENTHUOC, st.SOLUONG as SOLUONGTHUOC, st.KHOXUAT, st.GHICHU from
(
select nv.TENNHANVIEN as TENBACSI, ntkb.SOTHUTUTOA as SOTOATHUOC, d.TENDUOCDAYDU as TENTHUOC, nttt.SOLUONG as SOLUONG, ntkb.KHOXUAT_ID as KHOXUAT, nttt.GHICHU as GHICHU from TT_NGOAITRU_KHAMBENH_TOATHUOC as ntkb
inner join TT_NGOAITRU_TOATHUOC as nttt on nttt.KHAMBENH_TOATHUOC_ID = ntkb.KHAMBENH_TOATHUOC_ID
inner join TM_NHANVIEN as nv on nv.NHANVIEN_ID = ntkb.BACSI_ID
inner join TT_DUOC_CHUNGTU as ct on ntkb.CHUNGTUPHATTHUOC_ID = ct.CHUNGTU_ID
inner join TT_DUOC_CHUNGTU_CHITIET as ctct on ctct.CHUNGTU_ID = ct.CHUNGTU_ID
left join TM_DUOC as D on d.DUOC_ID = ctct.DUOC_ID
where ntkb.KHOXUAT_ID = #KHODUOC_ID or #KHODUOC_ID is null and CONVERT(DATE, CT.NGAYCHUNGTU) BETWEEN CONVERT(DATE,#TUNGAY) AND CONVERT(DATE,#DENNGAY)
group by nv.TENNHANVIEN, ntkb.SOTHUTUTOA, d.TENDUOCDAYDU, nttt.SOLUONG, ntkb.KHOXUAT_ID , nttt.GHICHU
union all
select nv.TENNHANVIEN as TENBACSI, NTT.SOTHUTUTOA as SOTOATHUOC, d.TENDUOCDAYDU as TENTHUOC, ntt.SOLUONG as SOLUONG, NKB.KHODUOC_ID as KHOXUAT, NTT.GHICHU as GHICHU from TT_NOITRU_KHAMBENH as NKB
inner join TT_NOITRU_TOATHUOC as NTT on NKB.KHAMBENH_ID = NTT.KHAMBENH_ID
inner join TM_NHANVIEN as nv on nv.NHANVIEN_ID = NKB.BACSIKHAM_ID
inner join TT_DUOC_CHUNGTU as ct on NTT.CHUNGTU_ID = ct.CHUNGTU_ID
inner join TT_DUOC_CHUNGTU_CHITIET as ctct on ctct.CHUNGTU_ID = ct.CHUNGTU_ID
left join TM_DUOC as D on d.DUOC_ID = ctct.DUOC_ID
where NKB.KHODUOC_ID = #KHODUOC_ID or #KHODUOC_ID is null and CONVERT(DATE, CT.NGAYCHUNGTU) BETWEEN CONVERT(DATE,#TUNGAY) AND CONVERT(DATE,#DENNGAY)
group by nv.TENNHANVIEN, NTT.SOTHUTUTOA, d.TENDUOCDAYDU, ntt.SOLUONG, NKB.KHODUOC_ID, NTT.GHICHU
) st where st.TENBACSI like '%' + #TENBACSI + '%'
group by st.TENBACSI, st.SOTOATHUOC, st.TENTHUOC, st.SOLUONG, st.KHOXUAT, st.GHICHU
order by st.TENBACSI
From that i used report builder to build a report where I group the TENBACSI aka doctors name and the SOTHUTUTOA aka the case id :
[1]: https://i.stack.imgur.com/NucZh.png
but when I tried to created row number for the 1st by using:
=RowNumber("TENBACSI")
It return wield Num Id such:
[2]: https://i.stack.imgur.com/HhDww.png
Then I tried to used:
=RunningValue(Fields!TENBACSI.Value,Count,"GROUP1")
Then I the result of all 1 in row number id.
I tried to look for answer but there is not much help

Data show by list when group by is not include data

I have a sql command like this
select mainPOID.EstAPDate,mainPOID.POID,TTm.ID,TTMAmount=TTMD.InvoiceAmount
From TTBeforeMms TTM
inner join TTBeforeMms_Detail TTMD on TTM.ID = TTMD.ID
inner join (
select distinct main.EstAPDate,main_D.POID
From AP main
left join AP_Detail main_D on main.ID = main_D.ID
where main.Type ='PA' and main.EstAPDate between '2018/6/01' AND '2018/6/15' and left(main_D.InvoiceNo,4) != '1111' ) mainPOID on TTMD.poid =mainPOID.POID and TTM.EstAPdate<=mainPOID.EstAPdate and mainPOID.POID='CM3PU18030009'
order by mainPOID.EstAPDate,mainPOID.POID
sql result will like this
My question is
How can Data show by list when group by is not include data?
For example
ID will show by list When I group by EstAPDate、POID and sum(TTMAmount)
You can store in one temp table or use CTE
CREATE TABLE [dbo].#Columnss(
espapdate date ,
poid varchar(max),
id varchar(max),amount decimal(22,6))
GO
insert into #Columnss values('2018-06-15','cm3','pt20',19988.8900)
insert into #Columnss values('2018-06-15','cm3','pt21',265.8900)
SELECT
REPLACE(ESPAPDATE,'-','/') ESPAPDATE, POID,
STUFF(
(SELECT ' , ' + OD.ID
FROM #COLUMNSS OD
WHERE OD.ESPAPDATE = O.ESPAPDATE
AND OD.POID = O.POID
FOR XML PATH('')), 1, 2, ''
) PRODUCTNAMES,SUM(AMOUNT)AMOUNT
FROM #COLUMNSS O
GROUP BY ESPAPDATE, POID
output
espapdate poid ProductNames amount
2018/06/15 cm3 pt20 , pt21 20254.780000
there are lots of CSV example using FOR XML PATH. For your case here, i am wrapping your existing query in a CTE and then from there generate the CSV string for ID
; with
cte as
(
select mainPOID.EstAPDate, mainPOID.POID, TTm.ID, TTMAmount=TTMD.InvoiceAmount
From TTBeforeMms TTM
inner join TTBeforeMms_Detail TTMD on TTM.ID = TTMD.ID
inner join (
select distinct main.EstAPDate,main_D.POID
From AP main
left join AP_Detail main_D on main.ID = main_D.ID
where main.Type ='PA'
and main.EstAPDate between '2018/6/01' AND '2018/6/15'
and left(main_D.InvoiceNo,4) != '1111'
) mainPOID on TTMD.poid = mainPOID.POID
and TTM.EstAPdate <= mainPOID.EstAPdate
and mainPOID.POID = 'CM3PU18030009'
)
SELECT EstAPDate, POID,
ID = STUFF(c.ID, 1, 1, ''),
TTMAmount = SUM(TTMAmount)
FROM cte
CROSS APPLY
(
SELECT ',' + ID
FROM cte x
WHERE x.EstAPDate = cte.EstAPDate
AND x.POID = cte.POID
FOR XML PATH ('')
) c (ID)
GROUP BY EstAPDate, POID
ORDER BY EstAPDate, POID

SQL to XML, combining two nodes

Currently I have a large SQL Server script that is outputting to XML. To summarize one of the nodes is duplicating. Below is the relevant snippet. I am looking consolidate some of the nodes into one but can't seem to get the syntax correct. See below for current and desired output examples.
DECLARE #CRWGroups TABLE (ClientID INT, intRegistrationWizardID INT, nvhProfileItemName VARCHAR(MAX), intProfileItemID INT, bitSelected BIT, intProfileItemOptionItemID INT, bitAnswer BIT
,dteAnswerStart DATE, decWeight DEC(5,2))
INSERT INTO #CRWGroups (ClientID, intRegistrationWizardID, nvhProfileItemName, intProfileItemID, bitSelected, intProfileItemOptionItemID, bitAnswer, dteAnswerStart, decWeight)
SELECT crw.intClientID, crw.intRegistrationWizardID, pi.nvhProfileItemName, crwegipi.intProfileItemID, crwegipi.bitSelected, pioi.intProfileItemOptionItemID,
crwegipib.bitAnswer, crwegipid.dteAnswerStart, pioi.decWeight from tblClientRegistrationWizard crw
INNER JOIN tblClientRegistrationWizardElement crwe ON crwe.intClientRegistrationWizardID = crw.intClientRegistrationWizardID
INNER JOIN tblClientRegistrationWizardElementGroup crweg ON crweg.intClientRegistrationWizardElementID = crwe.intClientRegistrationWizardElementID
LEFT JOIN tblClientRegistrationWizardElementGroupItem_ProfileItem crwegipi ON crwegipi.intClientRegistrationWizardElementGroupID = crweg.intClientRegistrationWizardElementGroupID
LEFT JOIN tblClientRegistrationWizardElementGroupItem_ProfileItemOptionItem crwegipioi ON crwegipioi.intClientRegistrationWizardElementGroupItemProfileItemID = crwegipi.intClientRegistrationWizardElementGroupItemProfileItemID
LEFT JOIN tblClientRegistrationWizardElementGroupItem_ProfileItemBool crwegipib ON crwegipib.intClientRegistrationWizardElementGroupItemProfileItemID = crwegipi.intClientRegistrationWizardElementGroupItemProfileItemID
LEFT JOIN tblClientRegistrationWizardElementGroupItem_ProfileItemDate crwegipid ON crwegipid.intClientRegistrationWizardElementGroupItemProfileItemID = crwegipi.intClientRegistrationWizardElementGroupItemProfileItemID
LEFT join tblProfileItem pi ON pi.intProfileItemID = crwegipi.intProfileItemID
LEFT JOIN tblProfileItemOptionItem pioi ON pioi.intProfileItemOptionItemID = crwegipioi.intProfileItemOptionItemID
LEFT JOIN tblProfileItemBool pib ON pib.intProfileItemID = crwegipib.intClientRegistrationWizardElementGroupItemProfileItemID
WHERE crw.intRegistrationWizardID = 49 AND (crwegipi.bitSelected = 1 OR crwegipib.bitAnswer = 1)
SELECT(
SELECT
(SELECT DISTINCT
CASE WHEN cg.intProfileItemID IN (5174,4864) THEN '10'
WHEN cg.intProfileItemID = 4862 THEN '11' END
FROM #CRWGroups cg WHERE cg.intProfileItemID IN (5174,4864,4862) AND cg.ClientID = c.ClientID
FOR XML PATH ('EmpStat'),type)
,(SELECT DISTINCT
CASE WHEN cg.intProfileItemID IN (4864,5174,4862) THEN (SELECT ISNULL(CASE WHEN CONVERT(DATE, cg.dteAnswerStart) = '1900-01-01' THEN '' ELSE CONVERT(CHAR(10), cg.dteAnswerStart, 120) END, '')) END
FROM #CRWGroups cg WHERE cg.intProfileItemID IN (4864,5174,4862) AND cg.ClientID = c.ClientID
FOR XML PATH ('DateEmpStatApp'),type)
,(SELECT CASE WHEN cg.intProfileItemID IN (5180) THEN (SELECT 'LOU' AS 'ESMType', '2' AS 'ESMCode' FOR XML PATH ('EmploymentStatusMonitoring'),type) END)
,(SELECT CASE WHEN cg.intProfileItemID IN (4868) THEN (SELECT 'BSI' AS 'ESMType', '1' AS 'ESMCode' FOR XML PATH ('EmploymentStatusMonitoring'),type) END)
FROM #CRWGroups cg WHERE cg.ClientID = c.ClientID AND cg.intProfileItemID IN (5180,4868)
FOR XML PATH ('LearnerEmploymentStatus'),type)
FROM tblClient c
INNER JOIN tblClientRegistrationWizard crw ON crw.intClientID = c.ClientID WHERE crw.intRegistrationWizardID = 49
Currently this snippet will produce the following result:
<LearnerEmploymentStatus>
<EmpStat>11</EmpStat>
<DateEmpStatApp>2017-06-05</DateEmpStatApp>
<EmploymentStatusMonitoring>
<ESMType>BSI</ESMType>
<ESMCode>1</ESMCode>
</EmploymentStatusMonitoring>
</LearnerEmploymentStatus>
<LearnerEmploymentStatus>
<EmpStat>11</EmpStat>
<DateEmpStatApp>2017-06-05</DateEmpStatApp>
<EmploymentStatusMonitoring>
<ESMType>LOU</ESMType>
<ESMCode>2</ESMCode>
</EmploymentStatusMonitoring>
</LearnerEmploymentStatus>
I am hoping to get it exporting in this format:
<LearnerEmploymentStatus>
<EmpStat>11</EmpStat>
<DateEmpStatApp>2017-06-05</DateEmpStatApp>
<EmploymentStatusMonitoring>
<ESMType>BSI</ESMType>
<ESMCode>1</ESMCode>
</EmploymentStatusMonitoring>
<EmploymentStatusMonitoring>
<ESMType>LOU</ESMType>
<ESMCode>2</ESMCode>
</EmploymentStatusMonitoring>
</LearnerEmploymentStatus>
Note there is only one EmploymentStatus node and contained inside are the two EmploymentStatusMonitoring nodes.

Optimize SQL Server query for speed

How can I optimize my SQL Server query ? Here is the code that I want to optimize
CREATE TABLE #Temp
(
TransactionId int PRIMARY KEY,
TransactionStepId int
)
INSERT INTO #Temp(TransactionId, TransactionStepId)
SELECT
TransactionId, MAX(TransactionStepId) TransactionStepId
FROM
[WarehouseMgmt].[FactPaymentTrans] FPT
JOIN
WarehouseMgmt.DimTimeZone DTZ on FPT.[TimeId] = DTZ.TimeUTCId
WHERE
FactType = 'SOURCE'
AND (DTZ.TimeId BETWEEN #DimStartDate AND #DimEndDate)
GROUP BY
TransactionId
IF(UPPER(#ReportBy) = 'TRANSACTION')
BEGIN
SET #sql = '
INSERT INTO #Results (
[PaymentTypeId],
[TransactionDate],
[PaymentMethodId],
[3DSecureId],
[ProductId],
[ProductTypeId],
[TransactionStatusId],
[Amount],
[Currency],
[PlayerId],
[PlayerSourceOrigId],
[Username],
[FirstName],
[LastName],
[BrandId],
[VIPLevelId],
[MarketingChannelId],
[MarketingSourceId],
[CommentId],
[CommentRefId],
[AdminName],
[OriginalTransactionId],
[TransactionId],
[RelatedTransactionId],
[ProviderTransactionOrigId]
)
SELECT
DTST.[Id],
FPT.[StartTime],
FPT.[PaymentMethodId],
FPT.[3DSecureId],
FPT.[ProductId],
DPT.[Id],
FPT.[TransactionStatusId],
FPT.[Amount],
FPT.CurrencyId,
FPT.[PlayerId],
DPL.[SourceOrigId],
DPL.[Username],
DPL.[FirstName],
DPL.[LastName],
DPL.[BrandId],
DPL.[VIPLevelId],
DPL.[MarketingChannelId],
DPL.[MarketingSourceId],
FPT.[PaymentReasonTextId],
FPT_Ref.[PaymentReasonTextId],
FPT.CreatedByAdminId,
FPT.[OriginalTransactionId],
FPT.[TransactionId],
FPT_Ref.[OriginalTransactionId],
FPT.[ProviderTransactionOrigId]
FROM WarehouseMgmt.FactPaymentTrans AS FPT
JOIN #Temp T ON FPT.TransactionId = T.TransactionId AND FPT.TransactionStepId = T.TransactionStepId
JOIN WarehouseMgmt.DimTransactionStepType AS DTST ON FPT.[TransactionStepTypeId] = DTST.[Id]
JOIN WarehouseMgmt.DimPlayer AS DPL ON FPT.PlayerId = DPL.Id
JOIN WarehouseMgmt.DimProduct AS DP ON DP.Id = FPT.ProductId
JOIN WarehouseMgmt.DimProductType AS DPT ON DPT.Id = DP.ProductTypeId
--JOIN WarehouseMgmt.DimTimeZone DTZ on FPT.[TimeId] = DTZ.TimeUTCId
JOIN [WarehouseMgmt].[DimLoyaltyProgramLevel] DLPL ON DLPL.[Id]=DPL.VipLevelId
LEFT JOIN
(
SELECT FPT_Ref_1.TransactionId,FPT_Ref_1.FactType,FPT_Ref_1.OriginalTransactionId,FPT_Ref_1.[PaymentReasonTextId]
FROM WarehouseMgmt.FactPaymentTrans AS FPT_Ref_1
JOIN #Temp T ON T.TransactionId = FPT_Ref_1.OriginalTransactionId AND T.TransactionStepId = FPT_Ref_1.TransactionStepId
) AS FPT_Ref ON FPT_Ref.OriginalTransactionId = FPT.TransactionId AND FPT_Ref.FactType = ''SOURCE''
WHERE (FPT.FactType = ''SOURCE'') ' + #sqlFilters
I tried to put this
SELECT TransactionId,MAX(TransactionStepId) TransactionStepId
FROM [WarehouseMgmt].[FactPaymentTrans]
WHERE FactType = ''SOURCE''
GROUP BY TransactionId
in a temp table, but this is even worst that without temp table. I want to select latest TransactionId(thats made by MAX(TransactionStepId) and also to select last TransactionId in the left JOIN
My execution plan is:
Have you considered using ROW_NUMBER instead of joining your table twice? Please try this:
;WITH FactPaymentTrans_Last
AS (
SELECT *, ROW_NUMBER() OVER(PARTITION BY TransactionID ORDER BY TransactionStepID DESC) AS RN
FROM WarehouseMgmt.FactPaymentTrans
)
SELECT DTST.[Id]
, FPT.[StartTime]
, FPT.[PaymentMethodId]
, FPT.[3DSecureId]
, FPT.[ProductId]
, DPT.[Id]
, FPT.[TransactionStatusId]
, FPT.[Amount]
, FPT.CurrencyId
, FPT.[PlayerId]
, DPL.[SourceOrigId]
, DPL.[Username]
, DPL.[FirstName]
, DPL.[LastName]
, DPL.[BrandId]
, DPL.[VIPLevelId]
, DPL.[MarketingChannelId]
, DPL.[MarketingSourceId]
, FPT.[PaymentReasonTextId]
, FPT_Ref.[PaymentReasonTextId]
, FPT.CreatedByAdminId
, FPT.[OriginalTransactionId]
, FPT.[TransactionId]
, FPT_Ref.[OriginalTransactionId]
, FPT.[ProviderTransactionOrigId]
FROM FactPaymentTrans_Last AS FPT
INNER JOIN WarehouseMgmt.DimTransactionStepType AS DTST
ON FPT.[TransactionStepTypeId] = DTST.[Id]
INNER JOIN WarehouseMgmt.DimPlayer AS DPL
ON FPT.PlayerId = DPL.Id
INNER JOIN WarehouseMgmt.DimProduct AS DP
ON DP.Id = FPT.ProductId
WHERE FPT.RN = 1;
It's just a snippet to give you idea how you can use this to get latest TransactionIds based on its TransactionStepId.
If it's not enough - please post these:
Your table structure
Indices on them
Your execution plan
It will help to give you suggestions.
There are multiple factors which can improve query performance and one of them which can be done, without necessarily knowing details about indexes, database schema, data distribution etc. is the order of the JOINs in the query.
I have refactored your query and I think you should get the same result as before, but with an improved execution time:
SELECT DTST.[Id]
,FPT.[StartTime]
,FPT.[PaymentMethodId]
,FPT.[3DSecureId]
,FPT.[ProductId]
,DPT.[Id]
,FPT.[TransactionStatusId]
,FPT.[Amount]
,FPT.CurrencyId
,FPT.[PlayerId]
,DPL.[SourceOrigId]
,DPL.[Username]
,DPL.[FirstName]
,DPL.[LastName]
,DPL.[BrandId]
,DPL.[VIPLevelId]
,DPL.[MarketingChannelId]
,DPL.[MarketingSourceId]
,FPT.[PaymentReasonTextId]
,FPT_Ref.[PaymentReasonTextId]
,FPT.CreatedByAdminId
,FPT.[OriginalTransactionId]
,FPT.[TransactionId]
,FPT_Ref.[OriginalTransactionId]
,FPT.[ProviderTransactionOrigId]
FROM WarehouseMgmt.FactPaymentTrans AS FPT
INNER JOIN WarehouseMgmt.DimPlayer AS DPL
ON FPT.PlayerId = DPL.Id
INNER JOIN WarehouseMgmt.DimProduct AS DP
ON DP.Id = FPT.ProductId
INNER JOIN WarehouseMgmt.DimProductType AS DPT
ON DPT.Id = DP.ProductTypeId
INNER JOIN WarehouseMgmt.DimTransactionStepType AS DTST
ON FPT.[TransactionStepTypeId] = DTST.[Id]
WHERE (FPT.FactType = '' SOURCE '')
AND EXISTS (SELECT 1
FROM [WarehouseMgmt].[FactPaymentTrans]
WHERE FactType = '' SOURCE ''
AND FPT.TransactionId = TransactionId
AND FPT.TransactionStepId = TransactionStepId)
AND EXISTS (SELECT 1
FROM [WarehouseMgmt].[DimLoyaltyProgramLevel] DLPL
WHERE DLPL.[Id] = DPL.VipLevelId)
AND EXISTS (SELECT 1
FROM WarehouseMgmt.DimTimeZone DTZ
WHERE FPT.[TimeId] = DTZ.TimeUTCId
AND DTZ.TimeId BETWEEN #DimStartDate AND #DimEndDate)

SQL Random Item for each USER

I have been searching and cannot find the right way to do this. In my query below, What I need is one random C.CREDENTIALING_K for each U.USER_K. I know the newid() will be needed somewhere, I just cannot find the proper place to put it.
select
U.USER_K,
U.FULLNAME as 'Chg_By',
CONVERT(DATE,AL.AUDITDATETIME) as 'Verif_Date',
P.ID,
P.LONGNAME,
CONVERT(DATE,P.DATEOFBIRTH) as 'DOB',
C.entity_k,
R.DESCRIPTION as 'CVI_TYPE',
C.CREDENTIALING_K,
CG.GROUPDESCRIPTION,
C.APPLICATION_RECEIVED,
R1.DESCRIPTION as 'Cur_STATUS',
CONVERT(DATE,C.USERDEF_D3) as 'MSO_DUE_DT'
from
VisualCACTUS.AUDITLOG AL
JOIN VisualCACTUS.USERS U
on U.user_k = AL.USER_K
join VisualCACTUS.CREDENTIALING C
JOIN VisualCACTUS.PROVIDERS P
on P.provider_k = C.PROVIDER_K
JOIN visualcactus.CREDENTIALINGGROUP CG
on CG.CREDENTIALINGGROUP_K = C.CREDENTIALINGGROUP_K
JOIN VisualCACTUS.REFTABLE R
on R.reftable_k = CG.TYPE_RTK
JOIN VisualCACTUS.REFTABLE R1
ON R1.REFTABLE_K = C.CREDENTIALINGSTATUS_RTK
--JOIN VisualCACTUS.CREDENTIALINGASSIGNMENTS CA
--on CA.credentialing_k = CA.credentialing_k
on C.CREDENTIALING_K = AL.FILE_PRIMARYKEY
where
AUDITLOG_K in (select AUDITLOG_K from VisualCACTUS.AUDITLOG_RECORDLEVEL where TABLE_NAME = 'CREDENTIALING '
and
AUDITLOG_RECORDLEVEL_K in (SELECT AUDITLOG_RECORDLEVEL_K from VisualCACTUS.AUDITLOG_FIELDLEVEL where NEWVALUE_SHORT = 'D2680X38F3'))
and
C.USERDEF_L1 = 0
and
CG.TYPE_RTK NOT IN ('D2870MPPSO','D2LC0YR0AR','D2DD1EIY5X')
and
CG.TYPE_RTK NOT LIKE ('SSP%')
and
C.credentialing_k not in (select credentialing_k from VisualCACTUS.CREDENTIALINGASSIGNMENTS where EA_K in (select ea_k from visualcactus.entityassignments where entity_k in ('HCA0000039',
'HCA0000040',
'HCA0000041',
'HCA0000043',
'HCA0000096',
'HCA0000095',
'HCA0000337',
'HCA0000903',
'HCA0000904',
'HCA0000905',
'HCA0000906',
'HCA0000080')))
and
CONVERT(DATE, AUDITDATETIME) = DATEADD(day, -1, convert(date, GETDATE()))
order by 'Chg_By'
Make a correlated subquery to return random CREDENTIALING_K
CREDENTIALING_K=(select top 1 C1.CREDENTIALING_K
from VisualCACTUS.CREDENTIALING c1
Where P.provider_k = C1.PROVIDER_K
order by newid())
Note : If needed add the filter that you have used for VisualCACTUS.CREDENTIALING table inside subquery too