Getting data in appropriate format - sql

I have a table which contains two column.
Agency Code MCI Numb
----------------------------
a 1234
a 12345
b 11
I need to write a query in SQl so that it will give data in following format.
< AgencyCode>
<ID>a</ID>
<MCI_NUMB>1234</MCI_NUMB>
<MCI_NUMB>12345</MCI_NUMB>
</AgencyCode>
< AgencyCode>
<ID>b</ID>
<MCI_NUMB>11</MCI_NUMB>
</AgencyCode>

You would need to use FOR XML / XPATH queries.
Try something like this:
SELECT ID
, CAST(MCI_Numb AS xml).query('/') AS MCI_Numbs
FROM(SELECT DISTINCT ID
, (SELECT MCI_Numb
FROM myTable
WHERE ID = T.ID
FOR XML PATH(''))AS MCI_Numb
FROM myTable AS T)AS T2
FOR XML PATH ('AgencyCode');
Take a look at this link: It explains in detail how to manipulate the sql server into xml and vice versa.

You probably need to take a look at :
FOR XML: http://technet.microsoft.com/en-us/library/ms177410(v=SQL.105).aspx
and
PIVOT: http://technet.microsoft.com/en-us/library/ms177410(v=SQL.105).aspx
The first will allow you to return xml, the second will allow you to pivot your data

Related

How to store output using different unique key (tried CROSS APPLY STRING_SPLIT)?

I'm trying to understand how I can convert what is currently stored in my sql tbl. The LBid is the unique ID and the productString column contains all of the product IDs that exist within each LBid. I need to write a statement to store each individual product ID (stored within productString) as the unique ID with all the associated LBids in a CSV format.
Current output
LBid title noProducts productString
51631 Slide2 NULL NULL
51636 Slide3 1 49518
51638 Slide4 1 49512
51641 Slide5 2 49512,49518
51643 Slide6 4 49512,46163,49518,46157
51645 Slide7 3 49874,47339,46165
51647 Slide8 5 49874,48807,49934,46766,47339
51649 Slide9 7 46165,48807,49874,47339,46766,47648,47948
Desired output
Product ID LBid
49518 51636,51641,51643
49512 51638,51641,51643
etc...
I've tried using the following code which helps me to split out the productString column, but I don't know how to save the output from this SELECT statemnet.
SELECT value, LBid, title, noProducts, productString
FROM dbo.LB
CROSS APPLY STRING_SPLIT(productString, ',')
GROUP BY value, LBid, title, noProducts, productString
ORDER BY value;
Output from above statement (this is a sample, may not directly reflect above code)
value id title productString
45891 52316 Slide337 45891,47205,47205,47209,47209,47443,47447,49246,47131,48744,48746
45909 52708 Slide533 47260,47248,49204,50783,48817,47270
45911 52708 Slide533 47260,47248
45917 51893 Slide129 45917,47910,46073,46077,50119,48813,45921,46729,46708,46706
45921 51893 Slide129 45917,47910,46073,46077,50119,48813,45921,46729,46708,46706
45923 51843 Slide104 50299,50132,50130,49548,49496,49577,45923,50060,46706
45923 51845 Slide105 45923,49577,50132,48923,46706,49747
Any help would be greatly appreciated.
Thanks
SQL Azure / SMSS
I need to write a statement to store each individual product ID (stored within productString) as the unique ID with all the associated LBids in a CSV format.
You need to aggregate:
SELECT lb.LBid, STRING_AGG(s.value, ',')
FROM dbo.LB CROSS APPLY
STRING_SPLIT(lb.productString, ',') s
GROUP BY lb.LBid
ORDER BY lb.LBid;

Condensing Data from 4 Columns to 2

I'm trying to combine two sets of columns down to one set in SQL, where all sets have a common JobID and Date.
I want to take columns FrOpr and BkOpr and condense them down to one Opr field while also take their corresponding FrExtract and BkExtract fields down to one corresponding Extract field.
Any thoughts on how to do this?
All the response are much appreciated. I adapted one of the queries below and used it to create a column of data that I wanted to reference and extract from in a larger query.
The output gives me two columns, an Opr and Extract column. In the larger query, I'm looking to select just values from the new Extract column and then Sum them up as a "Completed" output. My problem is knowing where/how to splice/nest this in to the existing query. Any thoughts on how to do this without creating a temp table? I'll post the larger query I want to add this to
SELECT CONCAT(Operators.OprExtID,'CIREG') AS Processor, Convert(VARCHAR(8), Data.StartDateTime, 112) AS [Processed Date], CONCAT('DEPTRI',Machines.EquipmentType,'',JobTypes.JobTypeDesc,'',Jobs.JobName) AS [Activity Type], SUM(Data.Handled) AS Completed FROM dbo.Operators, dbo.Data DataInput, dbo.jobs jobs, dbo.Machines, dbo.JobTypes WITH (nolock) WHERE (Jobs.ID = Data.JobID AND Data.FrOpr = Operators.Operator AND Data.MachNo = Machines.MachNo AND Data.JobTypeID = JobTypes.JobTypeID)
Processor Processed Date Activity Type Completed 0023390_CIREG 20190116 DEPTRI_LWACS_EXTRACTION_UTGENERAL 43.61 0023390_CIREG 20190116 DEPTRI_MWACS_DOC PREP_AGGEN 7.76 0023390_CIREG 20190116 DEPTRI_SWACS_OPENING_UTGENERAL 808 –
Use UNION
SELECT JobId , Date , FrOpr AS Opr , FrExtract AS Extract
FROM< TableName>
WHERE FrOpr IS NOT NULL
UNION ALL
SELECT JobId , Date , BkOpr AS Opr , BkExtract AS Extract
FROM <TableName>
WHERE BkOpr IS NOT NULL
One option is a CROSS APPLY
Example
Select A.JobID
,A.Date
,B.*
From YourTable A
Cross Apply ( values (FrOpr,FrExtract)
,(BkOpr,BKExtract)
) B(Opr,Extract)
Welcome to Stack Overflow! In the future, please provide sample data and desired results in text form.
This is a pretty simple un-pivot, which I'd do with a Union:
Select
JobId
, Date
, FrOpr as Opr
, FrExtract as Extract
, 'Fr' as Source_Column_Set
From <table_name>
Where <whatever conditions your application requires>
Union
Select
JobId
, Date
, BkOpr as Opr
, BkExtract as Extract
, 'Bk' as Source_Column_Set
From <table_name>
Where <whatever conditions your application requires>
You can make that a CTE and sort the results any way you like.
p.s. I included Source_Column_Set to avoid data loss.

Using TSQL and For XML Path to generate XML output

I have 3 temp tables all populated by 3 independent queries and are associated to each other with a 1 to 1 relationship, these tables are DemographicRecord, GPRegistrationDetails, MaternityBookingDetails. The columns are different between all 3 but each share the PatientID key. My question is using XML Path how can I output XML from the 3 related datasets following the format below.
<MAT001MothersDemographics>
<LocalPatientIdMother>BLANKED</LocalPatientIdMother>
<OrgCodeLocalPatientIdMother>BLANKED</OrgCodeLocalPatientIdMother>
<OrgCodeRes>BLANKED</OrgCodeRes>
<NHSNumberMother>BLANKED</NHSNumberMother>
<NHSNumberStatusMother>BLANKED</NHSNumberStatusMother>
<PersonBirthDateMother>BLANKED</PersonBirthDateMother>
<Postcode>BLANKED</Postcode>
<EthnicCategoryMother>BLANKED</EthnicCategoryMother>
<PersonDeathDateTimeMother>BLANKED</PersonDeathDateTimeMother>
<MAT003GPPracticeRegistration>
<LocalPatientIdMother>BLANKED</LocalPatientIdMother>
<OrgCodeGMPMother>BLANKED</OrgCodeGMPMother>
<StartDateGMPRegistration>BLANKED</StartDateGMPRegistration>
<EndDateGMPRegistration>BLANKED</EndDateGMPRegistration>
<OrgCodeCommissioner>BLANKED</OrgCodeCommissioner>
</MAT003GPPracticeRegistration>
<MAT101BookingAppointmentDetails>
<AntenatalAppDate>BLANKED</AntenatalAppDate>
<LocalPatientIdMother>BLANKED</LocalPatientIdMother>
<EDDAgreed>BLANKED</EDDAgreed>
<EDDMethodAgreed>BLANKED</EDDMethodAgreed>
<PregnancyFirstContactDate>BLANKED</PregnancyFirstContactDate>
<PregnancyFirstContactCareProfessionalType>BLANKED</PregnancyFirstContactCareProfessionalType>
<LastMenstrualPeriodDate>BLANKED</LastMenstrualPeriodDate>
<PhysicalDisabilityStatusIndMother>BLANKED</PhysicalDisabilityStatusIndMother>
<FirstLanguageEnglishIndMother>BLANKED</FirstLanguageEnglishIndMother>
<EmploymentStatusMother>BLANKED</EmploymentStatusMother>
<SupportStatusMother>BLANKED</SupportStatusMother>
<EmploymentStatusPartner>BLANKED</EmploymentStatusPartner>
<PreviousCaesareanSections>BLANKED</PreviousCaesareanSections>
<PreviousLiveBirths>BLANKED</PreviousLiveBirths>
<PreviousStillBirths>BLANKED</PreviousStillBirths>
<PreviousLossesLessThan24Weeks>BLANKED</PreviousLossesLessThan24Weeks>
<SubstanceUseStatus>BLANKED</SubstanceUseStatus>
<SmokingStatus>BLANKED</SmokingStatus>
<CigarettesPerDay>BLANKED</CigarettesPerDay>
<AlcoholUnitsPerWeek>BLANKED</AlcoholUnitsPerWeek>
<FolicAcidSupplement>BLANKED</FolicAcidSupplement>
<MHPredictionDetectionIndMother>BLANKED</MHPredictionDetectionIndMother>
<PersonWeight>BLANKED</PersonWeight>
<PersonHeight>BLANKED</PersonHeight>
<ComplexSocialFactorsInd>BLANKED</ComplexSocialFactorsInd>
</MAT101BookingAppointmentDetails>
</MAT001MothersDemographics>
So far I have tried:
SELECT
(SELECT * FROM #temp2
JOIN #temp ON #temp2.LocalPatientIdMother = #temp.LocalPatientIdMother
JOIN #temp3 ON #temp2.LocalPatientIdMother = #temp3.LocalPatientIdMother
FOR XML PATH('MAT001'), TYPE) AS 'MAT001MothersDemographics'
FOR XML PATH(''), ROOT('root')
But this is not the correct shape, can someone advise how I can use TSQL and FOR XML PATH effectively so I can generate the above output? I am currently getting the demographics repeated for every record before the other data is displayed?
<MAT001MothersDemographics>
<MAT001>
<LocalPatientIdMother>BLANKED</LocalPatientIdMother>
<OrgCodeLocalPatientIdMother>BLANKED</OrgCodeLocalPatientIdMother>
<OrgCodeRes>BLANKED</OrgCodeRes>
<NHSNumberMother>BLANKED</NHSNumberMother>
<NHSNumberStatusMother>BLANKED</NHSNumberStatusMother>
<PersonBirthDateMother>BLANKED</PersonBirthDateMother>
<Postcode>BLANKED</Postcode>
<EthnicCategoryMother>BLANKED</EthnicCategoryMother>
<PersonDeathDateTimeMother>BLANKED</PersonDeathDateTimeMother>
</MAT001>
</MAT001MothersDemographics>
<MAT001MothersDemographics>
<MAT001>
<LocalPatientIdMother>BLANKED</LocalPatientIdMother>
<OrgCodeLocalPatientIdMother>BLANKED</OrgCodeLocalPatientIdMother>
<OrgCodeRes>BLANKED</OrgCodeRes>
<NHSNumberMother>BLANKED</NHSNumberMother>
<NHSNumberStatusMother>BLANKED</NHSNumberStatusMother>
<PersonBirthDateMother>BLANKED</PersonBirthDateMother>
<Postcode>BLANKED</Postcode>
<EthnicCategoryMother>BLANKED</EthnicCategoryMother>
<PersonDeathDateTimeMother>BLANKED</PersonDeathDateTimeMother>
</MAT001>
</MAT001MothersDemographics>
Thanks very much
I must admit, that your question is quite unclear... You post a lot not needed details (e.g. big XMLs), but you do not provide the necessary information like table's structures and sample data. For the future please read How to ask a good SQL question and How to create a MCVE
But - my magic crystall ball is back from cleaning! - I try a quick shot:
SELECT t.*
,(
SELECT *
FROM #temp2 AS t2
WHERE t.LocalPatientIdMother=t2.LocalPatientIdMother
FOR XML PATH('MAT003GPPracticeRegistration'),TYPE
) AS [*]
,(
SELECT *
FROM #temp3 AS t3
WHERE t.LocalPatientIdMother=t3.LocalPatientIdMother
FOR XML PATH('MAT101BookingAppointmentDetail'),TYPE
) AS [*]
FROM #temp AS t
FOR XML PATH('MAT001MothersDemographics');
This will return all columns of #temp1 and will nest the related rows of #temp2 and #temp3. This is based on the assumption, that you have one record for the given ID in each table only...

How to Take two SQL queries of a column of substrings to search database using the appended result of the other

I have two select statements that both contain a column of substrings that derived from a database table. They are substrings derived from a varchar that should be an XML, but were saved as varcars because they could be not well-formed and potentially invalid.
I am trying to take the table that results in the 1st query, a list of 50 Varchars, and search the database using the 2nd query. I could get from 0 to n SQLRelatesMessageID sets from each SQLmessageID if I use each row in the first query and append a string to get the node ("z4480" is an example here).
I have tried a cursor implementation but the performance detered me from finishing it. Join doesn't work if you try giving the substring column with an as alias. What steps should I do to get the overall list of SQLRelatesMessageIDs. My goal is to get all MessageLogId (3 in picture) given a NCPDPID.
I am using SQL Server Manager 2012.
--1--Recieves a list based on a given NCPDPID node Value
select substring(m.message, charindex('<MessageID>', m.message)+11, charindex('</MessageID>', m.message)-charindex('<MessageID>', m.message)-11) as
SQLmessageID from messagelog m where message like '%<NCPDPID>'+'1234567'+'</NCPDPID>%'
--2--Selects messageID from top select and searches RelatesToMessageID node
select substring(r.message, charindex('<RelatesToMessageID>', r.message)+20, charindex('</RelatesToMessageID>', r.message)-charindex('<RelatesToMessageID>', r.message)-20) as SQLRelatesMessageID, * from messagelog r
where message like ('%<RelatesToMessageID>'+'z4480'+'</RelatesToMessageID>%')
This works for this answer.
---main
SELECT * FROM
(
select substring(m.message, charindex('<MessageID>', m.message)+11, charindex('</MessageID>', m.message)-charindex('<MessageID>', m.message)-11) as SQLmessageID from messagelog m
where message like '%<NCPDPID>1234567</NCPDPID>%' and dateTime > '3/01/2016'
) a JOIN
(
select
substring(r.message, charindex('<RelatesToMessageID>', r.message)+20, charindex('</RelatesToMessageID>', r.message)-charindex('<RelatesToMessageID>', r.message)-20) as SQLRelatesMessageID,
message,
messagelogid from messagelog r
where
dateTime > '3/01/2016' AND
message LIKE ('%<RelatesToMessageID>%</RelatesToMessageID>%')
) b ON b.SQLRelatesMessageID = a.SQLmessageID

Need to convert SQL Query to LINQ

I have the following SQL query that I need to convert into LINQ with VB.NET
SELECT *
FROM (SELECT Id
,LocationCode
,LocationName
,ContactName
,ContactEmail
,Comments
,SBUName
,CreatedBy
,CreatedDtm
,ModifiedBy
,ModifiedDtm
,ROW_NUMBER() OVER (PARTITION BY LocationCode ORDER BY ID) AS RowNumber
FROM testDB ) as rows
WHERE ROWNUMBER = 1
There are many duplicates of location code so I only want to display one record of each and the user will be able to edit the information. Once they edit I will save the info for all records that are for that specific location code.
I couldn't use DISTINCT here, it would still bring back all of the data since the CreatedBy/ModifiedBy are different.
By using the following LINQ query to select all of the data, is there a way I can get the DISTINCT records for LocationCode out of it?
queryLocMaint = From MR In objcontextGSC.TestDB
Select MR.Id,
MR.LocationCode,
MR.LocationName,
MR.SBUName,
MR.ContactName,
MR.ContactEmail,
MR.Comments,
MR.CreatedBy,
MR.CreatedDtm,
MR.ModifiedBy,
MR.ModifiedDtm()
ROW_NUMBER is not supported in LINQ, maybe you can use this GROUP BY approach:
Dim q = From mr In objcontextGSC.TestDB
Group mr By mr.LocationCode Into LocationCodeGroup = Group
Select LocationCodeGroup.OrderBy(Function(mr) mr.Id).First()
This takes the first row of each LocationCode-group ordered by id.