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.
Related
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
Below is the query that I am running. Execution plan is at the bottom. It takes 8 minutes to complete and shows 'Query cost related to batch : 84%' in query plan.
I haves fixed some required non-cluster indexes but it saved hardly a minute in runtime.
Select distinct
ItemSolicitacao.IdItemSolicitacao As IdItemSolicitacao,
ItemSolicitacao.IdSolicitacao As IdSolicitacao,
ItemSolicitacao.IdItemAplicacao As IdItemAplicacao,
ItemSolicitacao.Mapeado As Mapeado,
ItemSolicitacao.IdFuncao As IdFuncao,
ItemSolicitacao.IdDepartamento As IdDepartamento,
ItemSolicitacao.IdDeptoGrupo As IdDeptoGrupo,
ItemSolicitacao.Removido As Removido,
ItemSolicitacao.AtividadeNome As AtividadeNome,
ItemSolicitacao.Acao As Acao,
Aplicacao.Nome As AplicacaoNome,
dbo.OwnersItemAplicacao(ItemSolicitacao.IdItemAplicacao, ItemSolicitacao.IdSolicitacao) As Owner,
case
when((select count(d.codigo) from ControleXerox..departamento as d
where d.deptoPai = Departamento.Codigo) != 0)
then 1
else 0
end as Grupo,
Departamento.Nome As DepartamentoNome,
DeptoOutro.Nome As DepartamentoGrupoNome,
Funcao.Nome As FuncaoNome,
TipoAplicacao.Nome As TipoAplicacaoNome,
TipoItemAplicacao.Nome As TipoItemAplicacaoNome,
ItemAplicacao.Nome As ItemAplicacaoNome
From
ItemSolicitacao
Inner Join
ItemAplicacao ON ItemSolicitacao.IdItemAplicacao = ItemAplicacao.IdItemAplicacao
Inner Join
Aplicacao ON ItemAplicacao.IdAplicacao = Aplicacao.IdAplicacao
Inner Join
TipoAplicacao ON TipoAplicacao.IdTipoAplicacao = Aplicacao.IdTipoAplicacao
Inner Join
TipoItemAplicacao ON ItemAplicacao.IdTipoItemAplicacao = TipoItemAplicacao.IdTipoItemAplicacao
left Join
ControleXerox..Departamento ON Departamento.Codigo = ItemSolicitacao.IdDepartamento
left Join
ControleXerox..Departamento as DeptoOutro ON DeptoOutro.Codigo = ItemSolicitacao.IdDeptoGrupo
left Join
ControleXerox..Funcao ON Funcao.Codigo = ItemSolicitacao.IdFuncao
Inner Join
AprovadorItemAplicacao ON AprovadorItemAplicacao.IdItemAplicacao = ItemAplicacao.IdItemAplicacao
Inner Join
Aprovador on AprovadorItemAplicacao.idAprovador = Aprovador.idAprovador
and AprovadorItemAplicacao.IdTipoAprovador = 1
https://www.brentozar.com/pastetheplan/?id=B1ND0biUQ
Please find the details of scalar function.
CREATE FUNCTION [dbo].[OwnersItemAplicacao]
(
#IdItemAplicacao INT
,#IdSolicitacao INT
)
RETURNS VARCHAR(2000)
AS
BEGIN
DECLARE #saida VARCHAR(2000)
SET #saida = ' '
DECLARE #owner VARCHAR(200)
DECLARE cur CURSOR
FOR
SELECT DISTINCT vc.Nome
FROM controlexerox..grupoEstacao
INNER JOIN controlexerox..view_colaboradores vc ON grupoEstacao.codEstacao = (
SELECT max(e.codigo)
FROM controlexerox..workflowItem wi
INNER JOIN controlexerox..estacao e ON e.codWorkflowItem = wi.codigo
AND wi.codigoItem = #IdSolicitacao
INNER JOIN controlexerox..grupoEstacao ge ON ge.codEstacao = e.codigo
AND ge.idItemAplicacao = #IdItemAplicacao
)
AND grupoEstacao.LoginS3Responsavel = vc.codigo
ORDER BY vc.Nome;
OPEN cur
FETCH NEXT
FROM cur
INTO #owner
WHILE ##FETCH_STATUS = 0
BEGIN
SET #saida = #saida + CHAR(10) + #owner
FETCH NEXT
FROM cur
INTO #owner
END
CLOSE cur
DEALLOCATE cur
RETURN substring(#saida, 3, len(#saida))
END
This code is 100% untested because I have nothing to work with. But something along these lines should let you completely eliminate that scalar function. Keep in mind that sql is a declarative language and works best with sets. Doing processing RBAR (row by agonizing row) is going to suck the life out of your server.
Give this code a shot and see if it gets you pointed the right way.
Select distinct
s.IdItemSolicitacao
, s.IdSolicitacao
, s.IdItemAplicacao
, s.Mapeado
, s.IdFuncao
, s.IdDepartamento
, s.IdDeptoGrupo
, s.Removido
, s.AtividadeNome
, s.Acao
, a.Nome As AplicacaoNome
--, dbo.OwnersItemAplicacao(s.IdItemAplicacao, s.IdSolicitacao) As Owner
, Owner = x.NameList
, case when (select count(d.codigo) from ControleXerox..departamento as dept where dept.deptoPai = d.Codigo) != 0 then 1 else 0 end as Grupo,
, d.Nome As DepartamentoNome
, DeptoOutro.Nome As DepartamentoGrupoNome
, f.Nome As FuncaoNome
, Tipoa.Nome As TipoAplicacaoNome
, Tipoia.Nome As TipoItemAplicacaoNome
, ia.Nome As ItemAplicacaoNome
From ItemSolicitacao s
Inner Join ItemAplicacao ia ON s.IdItemAplicacao = ia.IdItemAplicacao
Inner Join Aplicacao a ON ia.IdAplicacao = a.IdAplicacao
Inner Join TipoAplicacao Tipoa ON Tipoa.IdTipoAplicacao = a.IdTipoAplicacao
Inner Join TipoItemAplicacao Tipoia ON ia.IdTipoItemAplicacao = Tipoia.IdTipoItemAplicacao
left Join ControleXerox..Departamento d ON d.Codigo = s.IdDepartamento
left Join ControleXerox..Departamento as DeptoOutro ON DeptoOutro.Codigo = s.IdDeptoGrupo
left Join ControleXerox..Funcao f ON f.Codigo = s.IdFuncao
Inner Join AprovadorItemAplicacao Aprovadoria ON Aprovadoria.IdItemAplicacao = ia.IdItemAplicacao
Inner Join Aprovador ON Aprovadoria.idAprovador = Aprovador.idAprovador
and Aprovadoria.IdTipoAprovador = 1
outer apply
(
select NameList = STUFF((select char(10) + vc.Nome
FROM controlexerox..grupoEstacao ge
INNER JOIN controlexerox..view_colaboradores vc ON ge.codEstacao =
(
SELECT max(e.codigo)
FROM controlexerox..workflowItem wi
INNER JOIN controlexerox..estacao e ON e.codWorkflowItem = wi.codigo
AND wi.codigoItem = s.IdSolicitacao
INNER JOIN controlexerox..grupoEstacao ge ON ge.codEstacao = e.codigo
AND ge.idItemAplicacao = s.IdItemAplicacao
)
AND grupoEstacao.LoginS3Responsavel = vc.codigo
group by vc.Nome
ORDER BY vc.Nome
FOR XML PATH('')), 1, 1, '')
) x
How do I create Stored Procedure on these queries and he output should show which check the anomaly was captured from, along with all the relevant data.
SELECT cm.Cust_id, cm.cust_ref_id4, cm.cust_ref_id3, cm.plan_group, cm.Company_name, cm.Cust_firstname, cm.Cust_lastname
COALESCE(c.pkCustomerID, c2.fkCustomerID, c3.pkCustomerID, c4.pkCustomerID) AS pkCustomerID, c3.CompanyName FROM PRODUCTIONSQL.[SigmaPaTri].[dbo].[CUSTOMER_MASTER] cm
LEFT JOIN PHOENIX.CORE.dbo.Customers AS c ON cust_ref_id4 = c.pkCustomerID AND cm.cust_ref_id3 = c.pkCustomerID AND cm.cust_ref_id3 >= 1000000 AND cm.Cust_firstname + ' ' + cm.Cust_lastname = c.CompanyName
LEFT JOIN PHOENIX.CORE.dbo.Contracts AS c2 ON cm.cust_ref_id3 = c2.ConfirmationNumber
WHERE cm.cust_status IN ('A','P','R','G') AND COALESCE(c.pkCustomerID, c2.fkCustomerID) IS NULL ORDER BY cust_ref_id4;
and
SELECT [pkCustomerID],b.[pkContractID],[pkCustomerTypeID],[CustomerType],b.[ContractType] AS Contractype1,c.[ContractType]
AS Contractype2 FROM [CORE].[dbo].[Customers] a
JOIN [CORE].[dbo].[CustomerTypes] ON [pkCustomerTypeID] = [fkCustomerTypeID]
LEFT JOIN (SELECT [pkContractID],[ContractType],[fkCustomerID] FROM [CORE].[dbo].[Contracts]
JOIN [CORE].[dbo].[ContractTypes] ON [fkContractTypeID] = [pkContractTypeID] WHERE [ContractType] NOT LIKE 'Holdover%')b ON a.pkCustomerID=b.fkCustomerID
LEFT JOIN (SELECT [pkContractID],[fkCustomerID],[ContractType] FROM [CORE].[dbo].[Contracts]
JOIN [CORE].[dbo].[ContractTypes] ON [fkContractTypeID] = [pkContractTypeID] WHERE ContractType LIKE 'Holdover%')c ON b.fkCustomerID=c.fkCustomerID WHERE [CustomerType] IN ('Customer','Former Customer') AND (b.ContractType IS NULL OR c.ContractType IS NULL)
You question is lacking a very important piece of information, the explanation of what you are trying to do. I took a shot in the dark here as a guess to what you might be looking for. BTW, I ran this through a formatter so it was legible.
SELECT 'Found in query1'
,cm.Cust_id
,cm.cust_ref_id4
,cm.cust_ref_id3
,cm.plan_group
,cm.Company_name
,cm.Cust_firstname
,cm.Cust_lastname
,COALESCE(c.pkCustomerID, c2.fkCustomerID, c3.pkCustomerID, c4.pkCustomerID) AS pkCustomerID
,c3.CompanyName
FROM PRODUCTIONSQL.[SigmaPaTri].[dbo].[CUSTOMER_MASTER] cm
LEFT JOIN PHOENIX.CORE.dbo.Customers AS c ON cust_ref_id4 = c.pkCustomerID
AND cm.cust_ref_id3 = c.pkCustomerID
AND cm.cust_ref_id3 >= 1000000
AND cm.Cust_firstname + ' ' + cm.Cust_lastname = c.CompanyName
LEFT JOIN PHOENIX.CORE.dbo.Contracts AS c2 ON cm.cust_ref_id3 = c2.ConfirmationNumber
WHERE cm.cust_status IN (
'A'
,'P'
,'R'
,'G'
)
AND COALESCE(c.pkCustomerID, c2.fkCustomerID) IS NULL
SELECT 'Found in query 2'
,[pkCustomerID]
,b.[pkContractID]
,[pkCustomerTypeID]
,[CustomerType]
,b.[ContractType] AS Contractype1
,c.[ContractType] AS Contractype2
FROM [CORE].[dbo].[Customers] a
INNER JOIN [CORE].[dbo].[CustomerTypes] ON [pkCustomerTypeID] = [fkCustomerTypeID]
LEFT JOIN (
SELECT [pkContractID]
,[ContractType]
,[fkCustomerID]
FROM [CORE].[dbo].[Contracts]
INNER JOIN [CORE].[dbo].[ContractTypes] ON [fkContractTypeID] = [pkContractTypeID]
WHERE [ContractType] NOT LIKE 'Holdover%'
) b ON a.pkCustomerID = b.fkCustomerID
LEFT JOIN (
SELECT [pkContractID]
,[fkCustomerID]
,[ContractType]
FROM [CORE].[dbo].[Contracts]
INNER JOIN [CORE].[dbo].[ContractTypes] ON [fkContractTypeID] = [pkContractTypeID]
WHERE ContractType LIKE 'Holdover%'
) c ON b.fkCustomerID = c.fkCustomerID
WHERE [CustomerType] IN (
'Customer'
,'Former Customer'
)
AND (
b.ContractType IS NULL
OR c.ContractType IS NULL
)
I have the following view below. The second nested select is always returning null when I use the TOP(1) clause, but when I remove this clause it returns the data as expected, just more rows than is needed. Does anyone see anything that would explain this?
SELECT TOP (100) PERCENT
a.ITEMID AS Model
,id.CONFIGID
,id.INVENTSITEID AS SiteId
,id.INVENTSERIALID AS Serial
,it.ITEMNAME AS Description
,CASE WHEN it.DIMGROUPID LIKE '%LR-Y' THEN 'Y'
ELSE 'N'
END AS SerialNumberReqd
,ISNULL(it.PRIMARYVENDORID, N'') AS Vendor
,ISNULL(vt.NAME, N'') AS VendorName
,id.INVENTLOCATIONID AS Warehouse
,id.WMSLOCATIONID AS Bin
,ISNULL(CONVERT(varchar(12), CASE WHEN C.DatePhysical < '1901-01-01'
THEN NULL
ELSE C.DatePhysical
END, 101), N' ') AS DeliveryDate
,CASE WHEN (a.RESERVPHYSICAL > 0
OR C.StatusIssue = 1)
AND c.TransType = 0 THEN C.PONumber
ELSE ''
END AS SoNumber
,'' AS SoDetail
,ISNULL(C.PONumber, N'') AS RefNumber
,ISNULL(CONVERT(varchar(12), CASE WHEN ins.ProdDate < '1901-01-01'
THEN NULL
ELSE ins.PRODDATE
END, 101), N' ') AS DateReceived
,it.STKSTORISGROUPID AS ProdGroup
,ISNULL(CONVERT(varchar(12), CASE WHEN ins.ProdDate < '1901-01-01'
THEN NULL
ELSE ins.PRODDATE
END, 101), N' ') AS ProductionDate
,it.ITEMGROUPID
,it.STKSTORISGROUPID AS MerchandisingGroup
,CASE WHEN a.postedValue = 0
THEN (CASE WHEN D.CostAmtPosted = 0 THEN D.CostAmtPhysical
ELSE D.CostAmtPosted
END)
ELSE a.POSTEDVALUE
END AS Cost
,CASE WHEN a.PHYSICALINVENT = 0 THEN a.Picked
ELSE a.PhysicalInvent
END AS PhysicalOnHand
,ins.STKRUGSQFT AS RugSqFt
,ins.STKRUGVENDSERIAL AS RugVendSerial
,ins.STKRUGVENDDESIGN AS RugVendDesign
,ins.STKRUGEXACTSIZE AS RugExactSize
,ins.STKRUGCOUNTRYOFORIGIN AS RugCountryOfOrigin
,ins.STKRUGQUALITYID AS RugQualityId
,ins.STKRUGCOLORID AS RugColorId
,ins.STKRUGDESIGNID AS RugDesignId
,ins.STKRUGSHAPEID AS RugShapeId
,CASE WHEN (a.AVAILPHYSICAL > 0) THEN 'Available'
WHEN (id.WMSLOCATIONID = 'NIL') THEN 'Nil'
WHEN (a.RESERVPHYSICAL > 0)
AND (c.TransType = 0) THEN 'Committed'
WHEN (a.RESERVPHYSICAL > 0) THEN 'Reserved'
WHEN (id.WMSLOCATIONID LIKE '%-Q') THEN 'Damaged'
WHEN (a.Picked > 0) THEN 'Picked'
ELSE 'UNKNOWN'
END AS Status
,'' AS ReasonCode
,'' AS BaseModel
,ISNULL(CAST(ins.STKSTORISCONFIGINFO AS nvarchar(1000)), N'') AS StorisConfigInfo
,ISNULL(C.ConfigSummary, N'') AS ConfigSummary
FROM
dbo.INVENTSUM AS a WITH (NOLOCK)
INNER JOIN dbo.INVENTDIM AS id WITH (NOLOCK)
ON id.DATAAREAID = a.DATAAREAID
AND id.INVENTDIMID = a.INVENTDIMID
LEFT OUTER JOIN dbo.INVENTTABLE AS it WITH (NOLOCK)
ON it.DATAAREAID = a.DATAAREAID
AND it.ITEMID = a.ITEMID
LEFT OUTER JOIN dbo.VENDTABLE AS vt WITH (NOLOCK)
ON vt.DATAAREAID = it.DATAAREAID
AND vt.ACCOUNTNUM = it.PRIMARYVENDORID
LEFT OUTER JOIN dbo.INVENTSERIAL AS ins WITH (NOLOCK)
ON ins.DATAAREAID = id.DATAAREAID
AND ins.INVENTSERIALID = id.INVENTSERIALID
LEFT OUTER JOIN (SELECT TOP (1)
itt.ITEMID
,invt.INVENTSERIALID
,itt.DATEPHYSICAL AS DatePhysical
,itt.TRANSREFID AS PONumber
,itt.TRANSTYPE AS TransType
,itt.STATUSISSUE AS StatusIssue
,dbo.stkRowsToColumn(itt.INVENTTRANSID, 'STI') AS ConfigSummary
,itt.RECID
FROM
dbo.INVENTTRANS AS itt WITH (NOLOCK)
INNER JOIN dbo.INVENTDIM AS invt WITH (NOLOCK)
ON invt.DATAAREAID = itt.DATAAREAID
AND invt.INVENTDIMID = itt.INVENTDIMID
WHERE
(itt.DATAAREAID = 'STI')
AND (itt.TRANSTYPE IN (0, 2, 3, 8))
AND (invt.INVENTSERIALID <> '')
ORDER BY
itt.RECID DESC) AS C
ON C.ITEMID = a.ITEMID
AND C.INVENTSERIALID = id.INVENTSERIALID
LEFT OUTER JOIN (SELECT TOP (1)
itt2.ITEMID
,invt2.INVENTSERIALID
,itt2.COSTAMOUNTPOSTED AS CostAmtPosted
,itt2.COSTAMOUNTPHYSICAL + itt2.COSTAMOUNTADJUSTMENT AS CostAmtPhysical
,itt2.RECID
FROM
dbo.INVENTTRANS AS itt2 WITH (NOLOCK)
INNER JOIN dbo.INVENTDIM AS invt2 WITH (NOLOCK)
ON invt2.DATAAREAID = itt2.DATAAREAID
AND invt2.INVENTDIMID = itt2.INVENTDIMID
WHERE
(itt2.DATAAREAID = 'STI')
AND (itt2.TRANSTYPE IN (0, 2, 3, 4, 6, 8))
AND (invt2.INVENTSERIALID <> '')
ORDER BY
itt2.RECID DESC) AS D
ON D.ITEMID = a.ITEMID
AND D.INVENTSERIALID = id.INVENTSERIALID
WHERE
(a.DATAAREAID = 'STI')
AND (a.CLOSED = 0)
AND (a.PHYSICALINVENT > 0)
AND (it.ITEMGROUPID LIKE 'FG-%'
OR it.ITEMGROUPID = 'MULTISHIP')
ORDER BY
SiteId
,Warehouse
Presumably, the top value in the subquery doesn't meet the subsequent join conditions. That is, this condition is not met:
D.ITEMID = a.ITEMID AND D.INVENTSERIALID = id.INVENTSERIALID
You are using a left outer join, so NULL values are filled in.
EDIT:
To re-iterate. When you run it with top 1, there are no values (for at least some combinations of the two variables). So, NULL will be filled in for these values. After all, top 1 (with or without the parentheses) returns only one row.
When you run it returning multiple rows, presumably there are matches. For the rows that match, the corresponding values are put it. This is the way that left outer join works.
Gordon's answer is correct as to why I was getting a few rows when removing top and none when I had it. The subquery in question was returning all the rows in the InventTrans table (5 million+) so when I used top, it was just getting the first row which didn't have anything. I realized this was the case when I was trying random high values (e.g 50000) in the TOP clause.
The ultimate fix was to change the left outer joins on the C and D subqueries to Cross Apply, and then change the where clauses to better filter the table (e.g itt.itemid = a.itemid and invt1.inventserialid = id.inventserialid). Using that, I was able to use TOP 1 as expected.
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>