How can I PIVOT this data? - sql

First, sorry for the middling title. Didn't have a ton of success on that front.
So - I have a table of data that has one row for each volunteer shift a person is scheduled for. Many people, being generous with their time, have signed up for multiple shifts. What I would like is to PIVOT this data s.t. I end up with one row per person, with sets of columns for each shift. I've spent about 90 minutes on this so far, but can't figure out how to PIVOT without an aggregation function applied.
What I mean by this is that each person is scheduled for at least one shift, so each person's row would have their unique ID, their name, their phone number, and their region. Then there would be a set of columns for Shift1 - role/status/start time/end time/etc. - which everyone would have filled out since everyone has signed up for at least one shift. Then, the Shift2 set of columns would be populated for people who have signed up for 2+ shifts, Shift3 for people who signed up for 3+ shifts, etc.
My current table schema:
CREATE TABLE [dbo].[confirmexport](
[PersonID] [int] NULL,
[EventType] [varchar](14) NULL,
[Shift] [varchar](10) NULL,
[StartDate] [datetime] NULL,
[StartTime] [datetime] NULL,
[EndDate] [datetime] NULL,
[EndTime] [datetime] NULL,
[Location] [varchar](39) NULL,
[Role] [varchar](16) NULL,
[Status] [varchar](9) NULL,
[FirstName] [varchar](20) NULL,
[LastName] [varchar](22) NULL,
[Phone] [bigint] NULL,
[Region] [varchar](9) NULL
) ON [PRIMARY]
All columns but PersonID, FirstName, LastName, Phone, and Region are shift-specific.
In an ideal world, I'd end up with a table that looked something like so:
CREATE TABLE [dbo].[confirmexportpivoted](
[PersonID] [int] NULL,
[Phone] [bigint] NULL,
[FirstName] [varchar](20) NULL,
[LastName] [varchar](22) NULL,
[Region] [varchar](9) NULL,
[EventType1] [varchar](14) NULL,
[Shift1] [varchar](10) NULL,
[StartDate1] [datetime] NULL,
[StartTime1] [datetime] NULL,
[EndDate1] [datetime] NULL,
[EndTime1] [datetime] NULL,
[Location1] [varchar](39) NULL,
[Role1] [varchar](16) NULL,
[Status1] [varchar](9) NULL,
[EventType2] [varchar](14) NULL,
[Shift2] [varchar](10) NULL,
[StartDate2] [datetime] NULL,
[StartTime2] [datetime] NULL,
[EndDate2] [datetime] NULL,
[EndTime2] [datetime] NULL,
[Location2] [varchar](39) NULL,
[Role2] [varchar](16) NULL,
[Status2] [varchar](9) NULL
) ON [PRIMARY]
Except with as many sets of columns as necessary for my data. OR - if that's a deal-breaker, I can definitely make do with 3. Any suggestions?
Thanks in advance - I am super-confused and would appreciate any and all help.

Well It was hard to me to reproduce the whole table, so I've worked only with Start and End Dates and Times, but solution should work for any number of columns. You can test it in SQL FIDDLE
SQL FIDDLE EXAMPLE
declare #columns nvarchar(max), #stmt nvarchar(max)
declare #Temp_Columns table (RowNum int, COLUMN_NAME nvarchar(128))
insert into #Temp_Columns
select R.RowNum, c.COLUMN_NAME
from
(
select row_number() over (partition by c.PersonID, c.FirstName, c.LastName, c.Phone, c.Region order by c.StartDate asc, c.EndDate asc) as RowNum
from confirmexport as c
) as R
inner join INFORMATION_SCHEMA.[COLUMNS] as c on c.TABLE_NAME = 'confirmexport' and c.COLUMN_NAME not in ('PersonID', 'FirstName', 'LastName')
order by 1, 2
select #columns = isnull(#columns + ', ', '') +
'min(case when A.RowNum = ' + cast(T.RowNum as nvarchar(128)) +
' then A.[' + T.COLUMN_NAME + '] else null end) as [' +
T.COLUMN_NAME + cast(T.RowNum as nvarchar(128)) + ']'
from #Temp_Columns as T
select #stmt = '
select
A.PersonId, A.FirstName, A.LastName, A.Phone, A.Region,' + #columns + '
from
(
select
c.*,
row_number() over (partition by c.PersonID, c.FirstName, c.LastName, c.Phone, c.Region order by c.StartDate asc, c.EndDate asc) as RowNum
from confirmexport as c
) as A
group by
A.PersonId, A.FirstName, A.LastName, A.Phone, A.Region'
exec sp_executesql
#stmt = #stmt

Related

I can't figure out how to Order by with string_agg

I have this query (I am using SQL Server 2019) and is working fine (combining Dates and Notes into one column). However, the result I am looking for is to have the latest date show up first.
How can I achieve that from this query?
SELECT ID,
​(SELECT string_agg(​concat(Date, ': ', Notes), CHAR(13) + CHAR(10) + CHAR(13) + CHAR (10)) as Expr1​
FROM(SELECT DISTINCT nd.Notes, nd.Date
FROM dbo.ReleaseTrackerNotes AS nd
INNER JOIN dbo.ReleaseTracker AS ac4 ON ac4.ID = nd.ReleaseTrackerID
WHERE (ac4.ID = ac.ID)) AS z_1) AS vNotes
FROM dbo.ReleaseTracker AS ac
GROUP BY ID
I have tried the ORDER BY but is not working
Here is my table:
CREATE TABLE [dbo].[ReleaseTrackerNotes](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ReleaseTrackerID] [int] NULL,
[AOC_ModelID] [int] NULL,
[Date] [date] NULL,
[Notes] [nvarchar](800) NULL,
CONSTRAINT [PK_ReleaseTrackerNotes] PRIMARY KEY CLUSTERED
CREATE TABLE [dbo].[ReleaseTracker](
[ID] [int] IDENTITY(1,1) NOT NULL,
[AOC_ModelID] [int] NOT NULL,
[MotherboardID] [int] NOT NULL,
[StatusID] [int] NOT NULL,
[TestCateoryID] [int] NULL,
[TestTypeID] [int] NULL,
[DateStarted] [date] NULL,
[DateCompleted] [date] NULL,
[LCS#/ORS#] [nvarchar](20) NULL,
[ETCDate] [date] NULL,
[CardsNeeded] [nvarchar](2) NULL,
CONSTRAINT [PK_Compatibility] PRIMARY KEY CLUSTERED
Use WITHIN GROUP (ORDER BY ...):
SELECT
ID,
STRING_AGG(​TRY_CONVERT(varchar, Date, 101) + ': ' + Notes +
CHAR(13) + CHAR(10) + CHAR(13), CHAR(10))
WITHIN GROUP (ORDER BY Date DESC) AS Expr1​
FROM
(
SELECT DISTINCT ac4.ID, nd.Notes, nd.Date
FROM dbo.ReleaseTrackerNotes AS nd
INNER JOIN dbo.ReleaseTracker AS ac4
ON ac4.ID = nd.ReleaseTrackerID
) AS vNotes
GROUP BY ID;

Error converting data type varchar to bigint in stored procedure

I'm trying to call this procedure with the usp_TimesheetsAuditsLoadAllbyId 42747, NULL command.
But I always get an error
Msg 8114, Level 16, State 5, Procedure usp_TimesheetsAuditsLoadAllById, Line 9
Error converting data type varchar to bigint.
The ID of TimesheetsAudits table is a bigint type. I tried several types of conversions and casts, but I'm really stuck right now.
Hope somebody can help. Thanks
ALTER PROCEDURE [dbo].[usp_TimesheetsAuditsLoadAllById]
(
#Id INT,
#StartDate DATETIME
)
AS
BEGIN
SET NOCOUNT ON
SELECT TOP 51 *
FROM
(SELECT TOP 51
ID,
Type,
ReferrerId,
CAST(Description AS VARCHAR(MAX)) AS Description,
OnBehalfOf,
Creator,
DateCreated
FROM
TimesheetsAudits
WHERE
(ReferrerID = #Id) AND
(#StartDate IS NULL OR DateCreated < #StartDate)
ORDER BY
DateCreated DESC
UNION
SELECT TOP 51
tia.ID,
tia.Type,
tia.ReferrerId,
'[Day: ' + CAST(DayNr AS VARCHAR(5)) + '] ' + CAST(tia.Description AS VARCHAR(MAX)) AS Description,
tia.OnBehalfOf,
tia.Creator,
tia.DateCreated
FROM
TimesheetItemsAudits tia
INNER JOIN
TimesheetItems ti ON tia.ReferrerId = ti.ID
WHERE
(ti.TimesheetID = #Id) AND
(#StartDate IS NULL OR tia.DateCreated < #StartDate)
ORDER BY
tia.DateCreated DESC) t
ORDER BY
t.DateCreated DESC
END
Table definition for tables from comments:
CREATE TABLE [dbo].[TimesheetsAudits](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[Type] [tinyint] NOT NULL,
[ReferrerId] [varchar](15) NOT NULL,
[Description] [text] NULL,
[OnBehalfOf] [varchar](10) NULL,
[Creator] [varchar](10) NOT NULL,
[DateCreated] [datetime] NOT NULL
)
CREATE TABLE [dbo].[TimesheetItemsAudits](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[Type] [tinyint] NOT NULL,
[ReferrerId] [varchar](15) NOT NULL,
[Description] [text] NULL,
[OnBehalfOf] [varchar](10) NULL,
[Creator] [varchar](10) NOT NULL,
[DateCreated] [datetime] NOT NULL
)
You perform an INNER JOIN of [dbo].[TimesheetsAudits] and TimesheetItems ti ON tia.ReferrerId = ti.ID
tia.[ReferrerId] is varchar and ti.[ID] is [bigint].
I'd expect a value in tia.[ReferrerId] that cannot be converted to bigint.
Try the following:
SELECT [ReferrerId] FROM TimesheetItemsAudits WHERE ISNUMERIC(ReferrerId) = 0
This may help you to find the "offending rows".

SQL to XML Output

I was hoping I could get some help with this last part of a somewhat complicated problem I have been working on.
We have to produce an XML file from a SQL table that we are generating.
At its core the XML needs three elements.
Patient
PhoneAssessment
F2FAssessment
This is working as I'll show in my test code. However, the one problem we have is that if someone has both a F2FAssessment and a PhoneAssessment it will generate multiple tags.
If you all could give me some insight on the best way to fix this to where there will only be one Patient tag that contains all possible PhoneAssessment and F2FAssessment tags it would be greatly appreciated.
Here is the SQL code:
use tempdb;
declare #t table
(
[people_id] [nvarchar](255) NULL,
[actual_date] [date] NULL,
[NPI] [int] NULL,
[FileCreationDate] [date] NULL,
[FileCreationTime] [time](7) NULL,
[ProviderPatientNo] [int] NULL,
[LastName] [nvarchar](255) NULL,
[FirstName] [nvarchar](255) NULL,
[SSN] [nvarchar](255) NULL,
[DOB] [date] NULL,
[Gender] [int] NULL,
[Race] [int] NULL,
[Ethnicity] [int] NULL,
[ProviderPhoneAssessmentId] [nvarchar](255) NULL,
[CallEndDate] [date] NULL,
[CallEndTime] [time](7) NULL,
[DispatchDate] [date] NULL,
[DispatchTime] [time](7) NULL,
[CallDisposition] [int] NULL,
[DispositionOther] [nvarchar](255) NULL,
[Notes] [nvarchar](255) NULL,
[ProviderF2FAssessmentId] [nvarchar](255) NULL,
[AssessmentDate] [date] NULL,
[ArrivalTime] [time](7) NULL,
[ResidentialStatus] [int] NULL,
[County] [int] NULL,
[EmploymentStatus] [int] NULL,
[MaritalStatus] [int] NULL,
[MilitaryStatus] [int] NULL,
[NumArrests30Days] [nvarchar](255) NULL,
[AttendedSchoolLast3Months] [int] NULL,
[EducationLevel] [int] NULL,
[PrimaryPayorSource] [int] NULL,
[SecondaryPayorSource] [int] NULL,
[AnnualHouseholdIncome] [int] NULL,
[NumberInHousehold] [int] NULL,
[CurrentServices] [int] NULL,
[MHTreatmentDeclaration] [int] NULL,
[MOTStatus] [int] NULL,
[DurablePOA] [int] NULL,
[AssessmentLocation] [nvarchar](255) NULL,
[TransportedByLE] [int] NULL,
[TelevideoAssessment] [int] NULL,
[CurrentDetoxSymptoms] [int] NULL,
[HistoryOfDetoxSymptoms] [int] NULL,
[PrimaryDSMDiagnosis] [nvarchar](255) NULL,
[SecondaryDSMDiagnosis] [nvarchar](255) NULL,
[CompletedByLastName] [nvarchar](255) NULL,
[CompletedByFirstName] [nvarchar](255) NULL,
[DateDispositionCompleted] [date] NULL,
[TimeDispositionCompleted] [time](7) NULL,
[RecommendedTransportMode] [int] NULL,
[DateTransportedToFacility] [date] NULL,
[TimeTransportedToFacility] [time](7) NULL,
[FollowupContacted] [nvarchar](255) NULL,
[FollowupReportedServiceHelpful] [nvarchar](255) NULL,
[ContactAttempts] [nvarchar](255) NULL,
[VoluntaryAdmissionRecommended] [nvarchar](255) NULL,
[AdmissionAssessmentViaTelehealth] [nvarchar](255) NULL,
[IsAdmitted] [nvarchar](255) NULL,
[FirstHospitalization] [nvarchar](255) NULL,
[PrimaryProblem] [nvarchar](255) NULL,
[IntellectualDisability] [int] NULL,
[MedicalInstability] [int] NULL,
[MedicationIssues] [int] NULL,
[PastTrauma] [int] NULL,
[SubstanceAbuse] [int] NULL,
[Drug] [int] NULL,
[DrugRoute] [int] NULL,
[DrugFrequency] [int] NULL,
[HospAlternative] [nvarchar](255) NULL,
[HospAltDisposition] [nvarchar](255) NULL,
[Hospitalization] [nvarchar](255) NULL,
[HospitalizationDisposition] [nvarchar](255) NULL,
[SCS_Stf_Recommend] [nvarchar](255) NULL
)
insert INTO #t
([people_id],[actual_date],[NPI],[FileCreationDate],[FileCreationTime],[ProviderPatientNo],[LastName],[FirstName],[SSN],[DOB],[Gender],[Race],[Ethnicity],[ProviderPhoneAssessmentId],[CallEndDate],[CallEndTime],[DispatchDate],[DispatchTime],[CallDisposition],[DispositionOther],[Notes],[ProviderF2FAssessmentId],[AssessmentDate],[ArrivalTime],[ResidentialStatus],[County],[EmploymentStatus],[MaritalStatus],[MilitaryStatus],[NumArrests30Days],[AttendedSchoolLast3Months],[EducationLevel],[PrimaryPayorSource],[SecondaryPayorSource],[AnnualHouseholdIncome],[NumberInHousehold],[CurrentServices],[MHTreatmentDeclaration],[MOTStatus],[DurablePOA],[AssessmentLocation],[TransportedByLE],[TelevideoAssessment],[CurrentDetoxSymptoms],[HistoryOfDetoxSymptoms],[PrimaryDSMDiagnosis],[SecondaryDSMDiagnosis],[CompletedByLastName],[CompletedByFirstName],[DateDispositionCompleted],[TimeDispositionCompleted],[RecommendedTransportMode],[DateTransportedToFacility],[TimeTransportedToFacility],[FollowupContacted],[FollowupReportedServiceHelpful],[ContactAttempts],[VoluntaryAdmissionRecommended],[AdmissionAssessmentViaTelehealth],[IsAdmitted],[FirstHospitalization],[PrimaryProblem],[IntellectualDisability],[MedicalInstability],[MedicationIssues],[PastTrauma],[SubstanceAbuse],[Drug],[DrugRoute],[DrugFrequency],[HospAlternative],[HospAltDisposition],[Hospitalization],[HospitalizationDisposition],[SCS_Stf_Recommend])
VALUES
('90F07844-746A-4347-82CA-39D4332B43F3','2013-09-25','1306875695','2014-02-12','15:19:37.0000000','108677','David','Joe','414555555','1999-01-23','2','1','2','59DC25C9-B659-42A3-B43D-26C741F9B929','2013-09-26','15:17:00.0000000',NULL,NULL,'1',NULL,NULL,NULL,NULL,NULL,NULL,'87',NULL,'6','4',NULL,NULL,NULL,'9','9',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,'LastName','Alisha','2013-09-26','15:17:00.0000000',NULL,NULL,NULL,'0',NULL,NULL,NULL,NULL,'0',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL),
('90F07844-746A-4347-82CA-39D4332B43F3','2013-09-25','1306875695','2014-02-12','15:19:37.0000000','108677','David','Joe','414555555','1999-01-23','2','1','2',NULL,'2013-09-25','18:45:00.0000000','2013-09-25','18:51:00.0000000','4',NULL,NULL,'35159D47-32B2-445C-A905-019E191FDDE2','2013-09-25','19:22:00.0000000','13','47','12','6','4',NULL,'3','23','8','9','0','4','8','3','3','3','4','0','0','0','0','V71.09 ','V71.09','Tweed','A','2013-09-25','21:10:51.0000000','3',NULL,NULL,'1','1',NULL,'0','0','0',NULL,'2','3','3','3','3','2',NULL,NULL,NULL,'8','4',NULL,NULL,NULL)
IF OBJECT_ID('tempdb.dbo.#Patient') IS NOT NULL drop table #Patient
IF OBJECT_ID('tempdb.dbo.#Drugs') IS NOT NULL drop table #Drugs
IF OBJECT_ID('tempdb.dbo.#Assessments') IS NOT NULL drop table #Assessments
IF OBJECT_ID('tempdb.dbo.#HospAlt') IS NOT NULL drop table #HospAlt
IF OBJECT_ID('tempdb.dbo.#HospDisp') IS NOT NULL drop table #HospDisp
IF OBJECT_ID('tempdb.dbo.#PatientDistinct') IS NOT NULL drop table #PatientDistinct
--Patient Distinct
select distinct
ProviderPatientNo
into #PatientDistinct
FROM #t
--Patients
select distinct
NPI,
FileCreationDate,
FileCreationTime,
ProviderPatientNo,
ProviderF2FAssessmentId,
ProviderPhoneAssessmentId,
people_id, LastName,FirstName,
SSN,[DOB],[Gender],[Race],[Ethnicity]
into #Patient
FROM #t
--Assessments
SELECT
CallEndDate,
CallEndTime,
DispatchDate,
DispatchTime,
CallDisposition,
DispositionOther,
Notes,
people_id,
ProviderPatientNo,
ProviderF2FAssessmentId,
ProviderPhoneAssessmentId,
AssessmentDate,
case when ArrivalTime is null then '07:00:00' else ArrivalTime end AS [ArrivalTime] ,
ResidentialStatus AS [ResidentialStatus],
County AS [County],
EmploymentStatus AS [EmploymentStatus],
MaritalStatus AS [MaritalStatus],
MilitaryStatus AS [MilitaryStatus],
NumArrests30Days AS [NumArrests30Days],
AttendedSchoolLast3Months AS [AttendedSchoolLast3Months],
EducationLevel AS [EducationLevel],
PrimaryPayorSource AS [PrimaryPayorSource],
SecondaryPayorSource AS [SecondaryPayorSource],
AnnualHouseholdIncome AS [AnnualHouseholdIncome],
NumberInHousehold AS [NumberInHousehold],
CurrentServices AS [CurrentServices],
MHTreatmentDeclaration AS [MHTreatmentDeclaration],
MOTStatus AS [MOTStatus],
DurablePOA AS [DurablePOA],
AssessmentLocation AS [AssessmentLocation],
TransportedByLE AS [TransportedByLE],
TelevideoAssessment AS [TelevideoAssessment],
CurrentDetoxSymptoms AS [CurrentDetoxSymptoms],
HistoryOfDetoxSymptoms AS [HistoryOfDetoxSymptoms],
PrimaryDSMDiagnosis AS [PrimaryDSMDiagnosis],
SecondaryDSMDiagnosis AS [SecondaryDSMDiagnosis],
CompletedByLastName AS [CompletedByLastName],
CompletedByFirstName AS [CompletedByFirstName],
DateDispositionCompleted AS [DateDispositionCompleted],
TimeDispositionCompleted AS [TimeDispositionCompleted],
RecommendedTransportMode AS [RecommendedTransportMode],
DateTransportedToFacility AS [DateTransportedToFacility],
TimeTransportedToFacility AS [TimeTransportedToFacility],
FollowupContacted AS [FollowupContacted],
FollowupReportedServiceHelpful AS [FollowupReportedServiceHelpful],
ContactAttempts AS [ContactAttempts],
VoluntaryAdmissionRecommended AS [VoluntaryAdmissionRecommended],
AdmissionAssessmentViaTelehealth AS [AdmissionAssessmentViaTelehealth],
IsAdmitted AS [IsAdmitted],
FirstHospitalization AS [FirstHospitalization],
PrimaryProblem AS [PrimaryProblem],
IntellectualDisability AS [IntellectualDisability],
MedicalInstability AS [MedicalInstability],
MedicationIssues AS [MedicationIssues],
PastTrauma AS [PastTrauma],
SubstanceAbuse AS [SubstanceAbuse]
into #Assessments
FROM #t
--Drugs
select ProviderF2FAssessmentId,
Drug,
DrugRoute,
DrugFrequency
into #Drugs
from #t
where ProviderF2FAssessmentId is not null
--HospAlternative
select
ProviderF2FAssessmentId,
HospAlternative,
HospAltDisposition
into #HospAlt
from #t
where ProviderF2FAssessmentId is not null
--Hospitalization
select
ProviderF2FAssessmentId,
1 as Hospitalization,
10 as HospitalizationDisposition
into #HospDisp
from #t
where ProviderF2FAssessmentId is not null
/*Create XML*/
declare #output XML
set #output =
--Provider Data
(
SELECT
NPI as [NPI],
FileCreationDate as [FileCreationDate],
cast(FileCreationTime as time) FileCreationTime,
(
--Patient Data
Select
Patient.ProviderPatientNo ,
LastName as [LastName],
FirstName as [FirstName],
SSN as [SSN],
DOB as [DOB],
Gender as [Gender],
Race as [Race],
Ethnicity as [Ethnicity],
--Phone Assessment Data
/*
<ProviderPhoneAssessmentId>52854541</ProviderPhoneAssessmentId>
<CallEndDate>2006-05-04</CallEndDate>
<CallEndTime>01:01:01.001</CallEndTime>
<DispatchDate>2006-05-04</DispatchDate>
<DispatchTime>01:01:01.001</DispatchTime>
<CallDisposition>1</CallDisposition>
<DispositionOther>DispositionOther0</DispositionOther>
<Notes>Notes0</Notes>
*/
(
Select
ProviderPhoneAssessmentId,
CallEndDate,
CallEndTime,
DispatchDate,
DispatchTime,
CallDisposition,
DispositionOther,
Notes
FROM #Assessments
WHERE ProviderPhoneAssessmentId is NOT NULL and ProviderPhoneAssessmentId = Patient.ProviderPhoneAssessmentId
FOR XML PATH(''), ELEMENTS, type) AS [PhoneAssessment/*],
--F2FAssessment
/*
<ProviderF2FAssessmentId>4343</ProviderF2FAssessmentId>
<AssessmentDate>2006-05-04</AssessmentDate>
<ArrivalTime>01:01:01.001</ArrivalTime>
<ResidentialStatus>1</ResidentialStatus>
<County>1</County>
<EmploymentStatus>1</EmploymentStatus>
<MaritalStatus>1</MaritalStatus>
<MilitaryStatus>1</MilitaryStatus>
<NumArrests30Days>50</NumArrests30Days>
<AttendedSchoolLast3Months>1</AttendedSchoolLast3Months>
<EducationLevel>1</EducationLevel>
<PrimaryPayorSource>1</PrimaryPayorSource>
<SecondaryPayorSource>1</SecondaryPayorSource>
<AnnualHouseholdIncome>0</AnnualHouseholdIncome>
<NumberInHousehold>128</NumberInHousehold>
<CurrentServices>1</CurrentServices>
<MHTreatmentDeclaration>1</MHTreatmentDeclaration>
<MOTStatus>1</MOTStatus>
<DurablePOA>1</DurablePOA>
<AssessmentLocation>1</AssessmentLocation>
<TransportedByLE>false</TransportedByLE>
<TelevideoAssessment>false</TelevideoAssessment>
<CurrentDetoxSymptoms>false</CurrentDetoxSymptoms>
<HistoryOfDetoxSymptoms>false</HistoryOfDetoxSymptoms>
<PrimaryDSMDiagnosis>PrimaryDS</PrimaryDSMDiagnosis>
<SecondaryDSMDiagnosis>Secondary</SecondaryDSMDiagnosis>
<CompletedByLastName>CompletedByLastName2</CompletedByLastName>
<CompletedByFirstName>CompletedByFirstName2</CompletedByFirstName>
<DateDispositionCompleted>2006-05-04</DateDispositionCompleted>
<TimeDispositionCompleted>01:01:01.001</TimeDispositionCompleted>
<RecommendedTransportMode>1</RecommendedTransportMode>
<DateTransportedToFacility>2006-05-04</DateTransportedToFacility>
<TimeTransportedToFacility>01:01:01.001</TimeTransportedToFacility>
<FollowupContacted>false</FollowupContacted>
<FollowupReportedServiceHelpful>false</FollowupReportedServiceHelpful>
<ContactAttempts>128</ContactAttempts>
<VoluntaryAdmissionRecommended>false</VoluntaryAdmissionRecommended>
<AdmissionAssessmentViaTelehealth>false</AdmissionAssessmentViaTelehealth>
<IsAdmitted>false</IsAdmitted><FirstHospitalization>1</FirstHospitalization>
<PrimaryProblem>1</PrimaryProblem><IntellectualDisability>1</IntellectualDisability>
<MedicalInstability>1</MedicalInstability>
<MedicationIssues>1</MedicationIssues>
<PastTrauma>1</PastTrauma>
<SubstanceAbuse>1</SubstanceAbuse>
*/
(SELECT
ProviderF2FAssessmentId as [F2FAssessment/ProviderF2FAssessmentId],
AssessmentDate as [F2FAssessment/AssessmentDate],
[ArrivalTime] as [F2FAssessment/ArrivalTime],
ResidentialStatus as [F2FAssessment/ResidentialStatus],
County as [F2FAssessment/County],
EmploymentStatus AS [F2FAssessment/EmploymentStatus],
MaritalStatus AS [F2FAssessment/MaritalStatus],
MilitaryStatus AS [F2FAssessment/MilitaryStatus],
NumArrests30Days AS [F2FAssessment/NumArrests30Days],
AttendedSchoolLast3Months AS [F2FAssessment/AttendedSchoolLast3Months],
EducationLevel AS [F2FAssessment/EducationLevel],
PrimaryPayorSource AS [F2FAssessment/PrimaryPayorSource],
SecondaryPayorSource AS [F2FAssessment/SecondaryPayorSource],
AnnualHouseholdIncome AS [F2FAssessment/AnnualHouseholdIncome],
NumberInHousehold AS [F2FAssessment/NumberInHousehold],
CurrentServices AS [F2FAssessment/CurrentServices],
MHTreatmentDeclaration AS [F2FAssessment/MHTreatmentDeclaration],
MOTStatus AS [F2FAssessment/MOTStatus],
DurablePOA AS [F2FAssessment/DurablePOA],
AssessmentLocation AS [F2FAssessment/AssessmentLocation],
TransportedByLE AS [F2FAssessment/TransportedByLE],
TelevideoAssessment AS [F2FAssessment/TelevideoAssessment],
CurrentDetoxSymptoms AS [F2FAssessment/CurrentDetoxSymptoms],
HistoryOfDetoxSymptoms AS [F2FAssessment/HistoryOfDetoxSymptoms],
PrimaryDSMDiagnosis AS [F2FAssessment/PrimaryDSMDiagnosis],
SecondaryDSMDiagnosis AS [F2FAssessment/SecondaryDSMDiagnosis],
CompletedByLastName AS [F2FAssessment/CompletedByLastName],
CompletedByFirstName AS [F2FAssessment/CompletedByFirstName],
DateDispositionCompleted AS [F2FAssessment/DateDispositionCompleted],
TimeDispositionCompleted AS [F2FAssessment/TimeDispositionCompleted],
RecommendedTransportMode AS [F2FAssessment/RecommendedTransportMode],
ISNULL(CAST(DateTransportedToFacility as varchar(30)),'xsi:nil="true"') AS [F2FAssessment/DateTransportedToFacility],
ISNULL(CAST(TimeTransportedToFacility as varchar(30)),'xsi:nil="true"')AS [F2FAssessment/TimeTransportedToFacility],
FollowupContacted AS [F2FAssessment/FollowupContacted],
FollowupReportedServiceHelpful AS [F2FAssessment/FollowupReportedServiceHelpful],
ContactAttempts AS [F2FAssessment/ContactAttempts],
VoluntaryAdmissionRecommended AS [F2FAssessment/VoluntaryAdmissionRecommended],
AdmissionAssessmentViaTelehealth AS [F2FAssessment/AdmissionAssessmentViaTelehealth],
IsAdmitted AS [F2FAssessment/IsAdmitted],
FirstHospitalization AS [F2FAssessment/FirstHospitalization],
PrimaryProblem AS [F2FAssessment/PrimaryProblem],
IntellectualDisability AS [F2FAssessment/IntellectualDisability],
MedicalInstability AS [F2FAssessment/MedicalInstability],
MedicationIssues AS [F2FAssessment/MedicationIssues],
PastTrauma AS [F2FAssessment/PastTrauma],
SubstanceAbuse AS [F2FAssessment/SubstanceAbuse]
,
(
SELECT
ISNULL(Drug,'') as Drug,
DrugRoute,
DrugFrequency
From #Drugs drugs
Where drugs.Drug is NOT NULL and drugs.ProviderF2FAssessmentId = #Assessments.ProviderF2FAssessmentId
FOR XML PATH(''), type) AS [F2FAssessment/F2FDrug]
,
(
SELECT
HospAlternative,
HospAltDisposition
From #HospAlt HospAlt
Where HospAlt.ProviderF2FAssessmentId = #Assessments.ProviderF2FAssessmentId
FOR XML PATH(''), type) AS [F2FAssessment/F2FHospAlternative]
,
(
SELECT
Hospitalization,
HospitalizationDisposition
From #HospDisp HospDisp
Where HospDisp.ProviderF2FAssessmentId = #Assessments.ProviderF2FAssessmentId
FOR XML PATH(''), type) AS [F2FAssessment/F2FHospitalization]
FROM #Assessments
Where ProviderF2FAssessmentId IS NOT NULL and ProviderF2FAssessmentId = Patient.ProviderF2FAssessmentId
FOR XML PATH(''), ELEMENTS, type) AS [*]
FROM #Patient Patient
FOR XML PATH('Patient'), type
)
from #t
group by NPI,FileCreationDate, FileCreationTime
for xml path('')
)
; with xmlnamespaces ('http://www.tn.gov/mental/Schemas/CrisisAssessment' AS "xsd", 'http://www.w3.org/2001/XMLSchema-instance' as "xsi")
select #output FOR XML PATH(''),TYPE, ROOT('Provider')
Here is an example of the XML output that I am currently getting:
<Provider xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.tn.gov/mental/Schemas/CrisisAssessment">
<NPI>1306875695</NPI>
<FileCreationDate>2014-02-12</FileCreationDate>
<FileCreationTime>15:19:37</FileCreationTime>
<Patient>
<ProviderPatientNo>108677</ProviderPatientNo>
<LastName>David</LastName>
<FirstName>Joe</FirstName>
<SSN>414555555</SSN>
<DOB>1999-01-23</DOB>
<Gender>2</Gender>
<Race>1</Race>
<Ethnicity>2</Ethnicity>
<PhoneAssessment>
<ProviderPhoneAssessmentId>59DC25C9-B659-42A3-B43D-26C741F9B929</ProviderPhoneAssessmentId>
<CallEndDate>2013-09-26</CallEndDate>
<CallEndTime>15:17:00</CallEndTime>
<CallDisposition>1</CallDisposition>
</PhoneAssessment>
</Patient>
<Patient>
<ProviderPatientNo>108677</ProviderPatientNo>
<LastName>David</LastName>
<FirstName>Joe</FirstName>
<SSN>414555555</SSN>
<DOB>1999-01-23</DOB>
<Gender>2</Gender>
<Race>1</Race>
<Ethnicity>2</Ethnicity>
<F2FAssessment>
<ProviderF2FAssessmentId>35159D47-32B2-445C-A905-019E191FDDE2</ProviderF2FAssessmentId>
<AssessmentDate>2013-09-25</AssessmentDate>
<ArrivalTime>19:22:00</ArrivalTime>
<ResidentialStatus>13</ResidentialStatus>
<County>47</County>
<EmploymentStatus>12</EmploymentStatus>
<MaritalStatus>6</MaritalStatus>
<MilitaryStatus>4</MilitaryStatus>
<AttendedSchoolLast3Months>3</AttendedSchoolLast3Months>
<EducationLevel>23</EducationLevel>
<PrimaryPayorSource>8</PrimaryPayorSource>
<SecondaryPayorSource>9</SecondaryPayorSource>
<AnnualHouseholdIncome>0</AnnualHouseholdIncome>
<NumberInHousehold>4</NumberInHousehold>
<CurrentServices>8</CurrentServices>
<MHTreatmentDeclaration>3</MHTreatmentDeclaration>
<MOTStatus>3</MOTStatus>
<DurablePOA>3</DurablePOA>
<AssessmentLocation>4</AssessmentLocation>
<TransportedByLE>0</TransportedByLE>
<TelevideoAssessment>0</TelevideoAssessment>
<CurrentDetoxSymptoms>0</CurrentDetoxSymptoms>
<HistoryOfDetoxSymptoms>0</HistoryOfDetoxSymptoms>
<PrimaryDSMDiagnosis>V71.09 </PrimaryDSMDiagnosis>
<SecondaryDSMDiagnosis>V71.09</SecondaryDSMDiagnosis>
<CompletedByLastName>Tweed</CompletedByLastName>
<CompletedByFirstName>A</CompletedByFirstName>
<DateDispositionCompleted>2013-09-25</DateDispositionCompleted>
<TimeDispositionCompleted>21:10:51</TimeDispositionCompleted>
<RecommendedTransportMode>3</RecommendedTransportMode>
<DateTransportedToFacility>xsi:nil="true"</DateTransportedToFacility>
<TimeTransportedToFacility>xsi:nil="true"</TimeTransportedToFacility>
<FollowupContacted>1</FollowupContacted>
<FollowupReportedServiceHelpful>1</FollowupReportedServiceHelpful>
<VoluntaryAdmissionRecommended>0</VoluntaryAdmissionRecommended>
<AdmissionAssessmentViaTelehealth>0</AdmissionAssessmentViaTelehealth>
<IsAdmitted>0</IsAdmitted>
<PrimaryProblem>2</PrimaryProblem>
<IntellectualDisability>3</IntellectualDisability>
<MedicalInstability>3</MedicalInstability>
<MedicationIssues>3</MedicationIssues>
<PastTrauma>3</PastTrauma>
<SubstanceAbuse>2</SubstanceAbuse>
<F2FHospAlternative>
<HospAlternative>8</HospAlternative>
<HospAltDisposition>4</HospAltDisposition>
</F2FHospAlternative>
<F2FHospitalization>
<Hospitalization>1</Hospitalization>
<HospitalizationDisposition>10</HospitalizationDisposition>
</F2FHospitalization>
</F2FAssessment>
</Patient>
</Provider>
Here is an example of how I need it to look:
<Provider xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.tn.gov/mental/Schemas/CrisisAssessment">
<NPI>1306875695</NPI>
<FileCreationDate>2014-02-12</FileCreationDate>
<FileCreationTime>15:19:37</FileCreationTime>
<Patient>
<ProviderPatientNo>108677</ProviderPatientNo>
<LastName>David</LastName>
<FirstName>Joe</FirstName>
<SSN>414555555</SSN>
<DOB>1999-01-23</DOB>
<Gender>2</Gender>
<Race>1</Race>
<Ethnicity>2</Ethnicity>
<PhoneAssessment>
<ProviderPhoneAssessmentId>59DC25C9-B659-42A3-B43D-26C741F9B929</ProviderPhoneAssessmentId>
<CallEndDate>2013-09-26</CallEndDate>
<CallEndTime>15:17:00</CallEndTime>
<CallDisposition>1</CallDisposition>
</PhoneAssessment>
<F2FAssessment>
<ProviderF2FAssessmentId>35159D47-32B2-445C-A905-019E191FDDE2</ProviderF2FAssessmentId>
<AssessmentDate>2013-09-25</AssessmentDate>
<ArrivalTime>19:22:00</ArrivalTime>
<ResidentialStatus>13</ResidentialStatus>
<County>47</County>
<EmploymentStatus>12</EmploymentStatus>
<MaritalStatus>6</MaritalStatus>
<MilitaryStatus>4</MilitaryStatus>
<AttendedSchoolLast3Months>3</AttendedSchoolLast3Months>
<EducationLevel>23</EducationLevel>
<PrimaryPayorSource>8</PrimaryPayorSource>
<SecondaryPayorSource>9</SecondaryPayorSource>
<AnnualHouseholdIncome>0</AnnualHouseholdIncome>
<NumberInHousehold>4</NumberInHousehold>
<CurrentServices>8</CurrentServices>
<MHTreatmentDeclaration>3</MHTreatmentDeclaration>
<MOTStatus>3</MOTStatus>
<DurablePOA>3</DurablePOA>
<AssessmentLocation>4</AssessmentLocation>
<TransportedByLE>0</TransportedByLE>
<TelevideoAssessment>0</TelevideoAssessment>
<CurrentDetoxSymptoms>0</CurrentDetoxSymptoms>
<HistoryOfDetoxSymptoms>0</HistoryOfDetoxSymptoms>
<PrimaryDSMDiagnosis>V71.09 </PrimaryDSMDiagnosis>
<SecondaryDSMDiagnosis>V71.09</SecondaryDSMDiagnosis>
<CompletedByLastName>Tweed</CompletedByLastName>
<CompletedByFirstName>A</CompletedByFirstName>
<DateDispositionCompleted>2013-09-25</DateDispositionCompleted>
<TimeDispositionCompleted>21:10:51</TimeDispositionCompleted>
<RecommendedTransportMode>3</RecommendedTransportMode>
<DateTransportedToFacility>xsi:nil="true"</DateTransportedToFacility>
<TimeTransportedToFacility>xsi:nil="true"</TimeTransportedToFacility>
<FollowupContacted>1</FollowupContacted>
<FollowupReportedServiceHelpful>1</FollowupReportedServiceHelpful>
<VoluntaryAdmissionRecommended>0</VoluntaryAdmissionRecommended>
<AdmissionAssessmentViaTelehealth>0</AdmissionAssessmentViaTelehealth>
<IsAdmitted>0</IsAdmitted>
<PrimaryProblem>2</PrimaryProblem>
<IntellectualDisability>3</IntellectualDisability>
<MedicalInstability>3</MedicalInstability>
<MedicationIssues>3</MedicationIssues>
<PastTrauma>3</PastTrauma>
<SubstanceAbuse>2</SubstanceAbuse>
<F2FHospAlternative>
<HospAlternative>8</HospAlternative>
<HospAltDisposition>4</HospAltDisposition>
</F2FHospAlternative>
<F2FHospitalization>
<Hospitalization>1</Hospitalization>
<HospitalizationDisposition>10</HospitalizationDisposition>
</F2FHospitalization>
</F2FAssessment>
</Patient>
</Provider>
Any help you can offer would be greatly appreciated.
This is working as I'll show in my test code. However, the one problem we have is that if someone has both a F2FAssessment and a PhoneAssessment it will generate multiple tags.
This happen because you insert the person record 2 times.
first insert: Person data + phoneAssesment data
second insert: Peson data + F2FAssessment
Table t has 2 records for person with NPI:1306875695
my suggestion is to modify the #t table,
Create #temp1 table, the #temp1 should only have person data + phoneAssesment
Create #temp2 table, the #temp2 only contain PersonID + F2FAssessment (PErsonId act as foreign key)
Insert the data, to both table.
Inner Join both table #temp1 and #temp2 as Table #t. Use the PersonId as the join condition.
Now table #t will have only 1 record for NPI: 1306875695
Try this suggestion, Hope this is help.
If you only want one Patient element, make the PhoneAssessment and F2F* statements sub queries:
WITH XMLNAMESPACES (DEFAULT 'http://www.tn.gov/mental/Schemas/CrisisAssessment')
SELECT
[NPI],
[FileCreationDate],
[FileCreationTime],
(
SELECT
ProviderPatientNo,
LastName, FirstName,
SSN, DOB, Gender,
Race, Ethnicity,
(
SELECT
ProviderPhoneAssessmentId, CallEndDate, CallEndTime, CallDisposition
FROM #t pa
WHERE ProviderPhoneAssessmentId is not null
and pa.ProviderPatientNo = p.ProviderPatientNo
FOR XML PATH('PhoneAssesment'), TYPE, ELEMENTS XSINIL
),
(
SELECT
ProviderF2FAssessmentId,
AssessmentDate, ArrivalTime, ResidentialStatus, County, EmploymentStatus,
MaritalStatus, MilitaryStatus, AttendedSchoolLast3Months, EducationLevel,
PrimaryPayorSource, SecondaryPayorSource, AnnualHouseholdIncome,
NumberInHousehold, CurrentServices, MHTreatmentDeclaration, MOTStatus,
DurablePOA, AssessmentLocation, TransportedByLE, TelevideoAssessment,
CurrentDetoxSymptoms, HistoryOfDetoxSymptoms, PrimaryDSMDiagnosis,
SecondaryDSMDiagnosis, CompletedByLastName, CompletedByFirstName,
DateDispositionCompleted, TimeDispositionCompleted, RecommendedTransportMode,
DateTransportedToFacility, TimeTransportedToFacility, FollowupContacted,
FollowupReportedServiceHelpful, VoluntaryAdmissionRecommended,
AdmissionAssessmentViaTelehealth, IsAdmitted, PrimaryProblem,
IntellectualDisability, MedicalInstability, MedicationIssues, PastTrauma,
SubstanceAbuse,
HospAlternative as [F2FHospAlternative/HospAlternative],
HospAltDisposition as [F2FHospAlternative/HospAltDisposition],
Hospitalization as [F2FHospitalization/Hospitalization],
HospitalizationDisposition as [F2FHospitalization/HospitalizationDisposition]
FROM #t f2f
WHERE f2f.ProviderF2FAssessmentId is not null
and f2f.ProviderPatientNo = p.ProviderPatientNo
GROUP BY ProviderF2FAssessmentId,
AssessmentDate, ArrivalTime, ResidentialStatus, County, EmploymentStatus,
MaritalStatus, MilitaryStatus, AttendedSchoolLast3Months, EducationLevel,
PrimaryPayorSource, SecondaryPayorSource, AnnualHouseholdIncome,
NumberInHousehold, CurrentServices, MHTreatmentDeclaration, MOTStatus,
DurablePOA, AssessmentLocation, TransportedByLE, TelevideoAssessment,
CurrentDetoxSymptoms, HistoryOfDetoxSymptoms, PrimaryDSMDiagnosis,
SecondaryDSMDiagnosis, CompletedByLastName, CompletedByFirstName,
DateDispositionCompleted, TimeDispositionCompleted, RecommendedTransportMode,
DateTransportedToFacility, TimeTransportedToFacility, FollowupContacted,
FollowupReportedServiceHelpful, VoluntaryAdmissionRecommended,
AdmissionAssessmentViaTelehealth, IsAdmitted, PrimaryProblem,
IntellectualDisability, MedicalInstability, MedicationIssues, PastTrauma,
SubstanceAbuse, HospAlternative, HospAltDisposition, Hospitalization,
HospitalizationDisposition
FOR XML PATH('F2FAssessment'), TYPE, ELEMENTS XSINIL
)
FROM #t p
GROUP BY ProviderPatientNo, LastName, FirstName, SSN, DOB, Gender, Race, Ethnicity
FOR XML PATH('Patient'), TYPE, ELEMENTS XSINIL
)
FROM (SELECT TOP(1) [NPI], [FileCreationDate], [FileCreationTime] FROM #t) as FileHeader
FOR XML PATH('Provider'), ELEMENTS XSINIL
Also, I am guessing you want xsi:nil="true" to be an attribute. That is achieved through the XSINIL option. Also, you reference a namespace, but do not use it. Do you mean to make it the default (WITH XMLNAMESPACES (DEFAULT 'http://www.tn.gov/mental/Schemas/CrisisAssessment'))?
Produces:
<Provider xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.tn.gov/mental/Schemas/CrisisAssessment">
<NPI>1306875695</NPI>
<FileCreationDate>2014-02-12</FileCreationDate>
<FileCreationTime>15:19:37</FileCreationTime>
<Patient xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.tn.gov/mental/Schemas/CrisisAssessment">
<ProviderPatientNo>108677</ProviderPatientNo>
<LastName>David</LastName>
<FirstName>Joe</FirstName>
<SSN>414555555</SSN>
<DOB>1999-01-23</DOB>
<Gender>2</Gender>
<Race>1</Race>
<Ethnicity>2</Ethnicity>
<PhoneAssesment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.tn.gov/mental/Schemas/CrisisAssessment">
<ProviderPhoneAssessmentId>59DC25C9-B659-42A3-B43D-26C741F9B929</ProviderPhoneAssessmentId>
<CallEndDate>2013-09-26</CallEndDate>
<CallEndTime>15:17:00</CallEndTime>
<CallDisposition>1</CallDisposition>
</PhoneAssesment>
<F2FAssessment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.tn.gov/mental/Schemas/CrisisAssessment">
<ProviderF2FAssessmentId>35159D47-32B2-445C-A905-019E191FDDE2</ProviderF2FAssessmentId>
<AssessmentDate>2013-09-25</AssessmentDate>
<ArrivalTime>19:22:00</ArrivalTime>
<ResidentialStatus>13</ResidentialStatus>
<County>47</County>
<EmploymentStatus>12</EmploymentStatus>
<MaritalStatus>6</MaritalStatus>
<MilitaryStatus>4</MilitaryStatus>
<AttendedSchoolLast3Months>3</AttendedSchoolLast3Months>
<EducationLevel>23</EducationLevel>
<PrimaryPayorSource>8</PrimaryPayorSource>
<SecondaryPayorSource>9</SecondaryPayorSource>
<AnnualHouseholdIncome>0</AnnualHouseholdIncome>
<NumberInHousehold>4</NumberInHousehold>
<CurrentServices>8</CurrentServices>
<MHTreatmentDeclaration>3</MHTreatmentDeclaration>
<MOTStatus>3</MOTStatus>
<DurablePOA>3</DurablePOA>
<AssessmentLocation>4</AssessmentLocation>
<TransportedByLE>0</TransportedByLE>
<TelevideoAssessment>0</TelevideoAssessment>
<CurrentDetoxSymptoms>0</CurrentDetoxSymptoms>
<HistoryOfDetoxSymptoms>0</HistoryOfDetoxSymptoms>
<PrimaryDSMDiagnosis>V71.09 </PrimaryDSMDiagnosis>
<SecondaryDSMDiagnosis>V71.09</SecondaryDSMDiagnosis>
<CompletedByLastName>Tweed</CompletedByLastName>
<CompletedByFirstName>A</CompletedByFirstName>
<DateDispositionCompleted>2013-09-25</DateDispositionCompleted>
<TimeDispositionCompleted>21:10:51</TimeDispositionCompleted>
<RecommendedTransportMode>3</RecommendedTransportMode>
<DateTransportedToFacility xsi:nil="true" />
<TimeTransportedToFacility xsi:nil="true" />
<FollowupContacted>1</FollowupContacted>
<FollowupReportedServiceHelpful>1</FollowupReportedServiceHelpful>
<VoluntaryAdmissionRecommended>0</VoluntaryAdmissionRecommended>
<AdmissionAssessmentViaTelehealth>0</AdmissionAssessmentViaTelehealth>
<IsAdmitted>0</IsAdmitted>
<PrimaryProblem>2</PrimaryProblem>
<IntellectualDisability>3</IntellectualDisability>
<MedicalInstability>3</MedicalInstability>
<MedicationIssues>3</MedicationIssues>
<PastTrauma>3</PastTrauma>
<SubstanceAbuse>2</SubstanceAbuse>
<F2FHospAlternative>
<HospAlternative>8</HospAlternative>
<HospAltDisposition>4</HospAltDisposition>
</F2FHospAlternative>
<F2FHospitalization>
<Hospitalization xsi:nil="true" />
<HospitalizationDisposition xsi:nil="true" />
</F2FHospitalization>
</F2FAssessment>
</Patient>
</Provider>

SQL select all records only if the sum is greater than 0

I have the following SQL;
ALTER PROCEDURE [dbo].[MyReport]
#startdate datetime,
#enddate datetime
AS
/* Return the event plan (coming events) for a specific volunteer */
declare #sd datetime
declare #ed datetime
/* Ensure that the start and end dates covert whole days */
set #sd = convert(varchar(10),#startdate,120) + ' 00:00:00'
set #ed = convert(varchar(10),#enddate,120) + ' 23:59:59'
SELECT
E.EventID, E.EventDate, E.StartTime, E.StartLocation, E.EndTime,
E.EndLocation, E.Charged, E.Actual,E.ChargeRate, E.Cost,
E.Persons, E.Reason,
C.ClientID, C.Address1, C.Address2,
C.Town, C.County, C.Postcode,
C.InvoiceName, C.InvoiceAddress1, C.InvoiceAddress2,
C.InvoiceTown, C.InvoiceCounty, C.InvoicePostCode,
ISNULL(C.Surname, '') + ', ' + ISNULL(C.Forename, '') AS ClientSurnameForename
FROM
vEvents E
INNER JOIN
vClients C ON E.ClientID = C.ClientID
WHERE
(E.EventDate BETWEEN #sd AND #ed)
AND E.SchemeID = 4
ORDER BY
c.Surname, c.Forename, E.EventDate, E.StartTime, E.EndTime
I need to sum the column E.Charged to check see if the amount for the client is greater than 0 before returning the recordset. I have tried the following:
ALTER PROCEDURE [dbo].[MyReport]
#startdate datetime,
#enddate datetime
AS
/* Return the event plan (coming events) for a specific volunteer */
declare #sd datetime
declare #ed datetime
/* Ensure that the start and end dates covert whole days */
set #sd = convert(varchar(10),#startdate,120) + ' 00:00:00'
set #ed = convert(varchar(10),#enddate,120) + ' 23:59:59'
SELECT
E.EventID, E.EventDate, E.StartTime, E.StartLocation, E.EndTime,
E.EndLocation, E.Charged, E.Actual,E.ChargeRate, E.Cost,
E.Persons, E.Reason,
C.ClientID, C.Address1, C.Address2, C.Town, C.County, C.Postcode,
C.InvoiceName, C.InvoiceAddress1, C.InvoiceAddress2, C.InvoiceTown,
C.InvoiceCounty, C.InvoicePostCode,
ISNULL(C.Surname, '') + ', ' + ISNULL(C.Forename, '') AS ClientSurnameForename
FROM
vEvents E
INNER JOIN
vClients C ON E.ClientID = C.ClientID
WHERE
vEvents.ClientID IN (SELECT vEvents.Charged
FROM vEvents
GROUP BY vEvents.ClientID, vEvents.charged
HAVING SUM(vEvents.Charged) > 0)
AND (E.EventDate BETWEEN #sd AND #ed)
AND E.SchemeID = 4
ORDER BY
c.Surname, c.Forename, E.EventDate, E.StartTime, E.EndTime
But I keep getting 'the multipart identifier could not be bound'. TIA Andrew
Table Structure
[vEvents](
[EventID] [int] IDENTITY(1,1) NOT NULL,
[ClientID] [int] NOT NULL,
[ChargeID] [int] NOT NULL,
[EventDate] [datetime] NULL,
[StartTime] [datetime] NULL,
[StartLocation] [nvarchar](50) NULL,
[EndTime] [datetime] NULL,
[EndLocation] [nvarchar](50) NULL,
[Reason] [nvarchar](50) NULL,
[Charged] [decimal](6, 2) NOT NULL,
[Actual] [decimal](6, 2) NOT NULL,
[Additional] [decimal](6, 2) NOT NULL,
[Done] [bit] NOT NULL,
[Verifier] [nvarchar](50) NULL,
[ChargeRate] [decimal](6, 4) NULL,
[TeamID] [int] NOT NULL,
[Combined] [bit] NOT NULL,
Its an edit list but contains the most relevant
The Client Table
[vClients](
[ClientID] [int] IDENTITY(1,1) NOT NULL,
[ManagerID] [int] NOT NULL,
[RegularID] [int] NOT NULL,
[Forename] [nvarchar](50) NULL,
[Surname] [nvarchar](50) NULL,
[Address1] [nvarchar](50) NULL,
[Address2] [nvarchar](50) NULL,
[Town] [nvarchar](50) NULL,
[County] [nvarchar](50) NULL,
[PostCode] [nvarchar](10) NULL,
[Telephone] [nvarchar](30) NULL,
[Comments] [ntext] NULL,
[ReviewDate] [datetime] NULL,
[Requirements] [int] NOT NULL,
[Status] [int] NOT NULL,
[EmergencyType] [nvarchar](50) NULL,
[EmergencyContact] [nvarchar](50) NULL,
[EmergencyNotes] [ntext] NULL,
[EmergencyTelephone] [nvarchar](50) NULL,
[Title] [nvarchar](50) NULL,
[VolunteerID] [int] NOT NULL,
[UserID] [int] NOT NULL,
[DateOfBirth] [datetime] NULL,
[HasPushPin] [bit] NULL,
[InvoiceAddress1] [nvarchar](50) NULL,
[InvoiceAddress2] [nvarchar](50) NULL,
[InvoiceTown] [nvarchar](50) NULL,
[InvoiceCounty] [nvarchar](50) NULL,
[InvoicePostcode] [nvarchar](10) NULL,
[InvoiceName] [nvarchar](50) NULL,
[Email] [nvarchar](50) NULL,
Try to change the WHERE part of your query to something like this:
WHERE
E.ClientID IN (SELECT vEvents.ClientID
FROM vEvents
GROUP BY vEvents.ClientID
HAVING SUM(vEvents.Charged) > 0)
AND ...
Maybe:
ALTER PROCEDURE [dbo].[MyReport]
#startdate datetime,
#enddate datetime
AS
/* Return the event plan (coming events) for a specific volunteer */
declare #sd datetime
declare #ed datetime
/* Ensure that the start and end dates covert whole days */
set #sd = convert(varchar(10),#startdate,120) + ' 00:00:00'
set #ed = convert(varchar(10),#enddate,120) + ' 23:59:59'
SELECT
E.EventID, E.EventDate, E.StartTime, E.StartLocation, E.EndTime,
E.EndLocation, E.Charged, E.Actual,E.ChargeRate, E.Cost,
E.Persons, E.Reason,
C.ClientID, C.Address1, C.Address2, C.Town, C.County, C.Postcode,
C.InvoiceName, C.InvoiceAddress1, C.InvoiceAddress2, C.InvoiceTown,
C.InvoiceCounty, C.InvoicePostCode,
ISNULL(C.Surname, '') + ', ' + ISNULL(C.Forename, '') AS ClientSurnameForename
FROM
vEvents E
INNER JOIN
vClients C ON E.ClientID = C.ClientID
INNER JOIN (SELECT ClientID, SUM(Charged) ch
FROM vEvents
GROUP BY ClientID
HAVING SUM(Charged) > 0) t
ON t.ClientID = vEvents.ClientID
WHERE (E.EventDate BETWEEN #sd AND #ed)
AND E.SchemeID = 4
ORDER BY
c.Surname, c.Forename, E.EventDate, E.StartTime, E.EndTime

Return rows which have same data in three columns

I have a table with the following schema
CREATE TABLE [dbo].[personas](
[id_persona] [int] IDENTITY(1,1) NOT NULL,
[nombres] [nvarchar](50) NOT NULL,
[apellido_paterno] [nvarchar](50) NULL,
[apellido_materno] [nvarchar](50) NULL,
[fecha_nacimiento] [date] NOT NULL,
[sexo] [varchar](1) NOT NULL,
[estado_civil] [nvarchar](50) NOT NULL,
[calle] [nvarchar](200) NULL,
[colonia] [nvarchar](100) NULL,
[codigo_postal] [char](5) NOT NULL,
[telefonos] [varchar](50) NULL,
[celular] [varchar](25) NULL,
[email] [varchar](50) NULL,
)
How do I make a query in SQL Server to return rows where nombre, apellido_paterno and apellido_materno are repeated? I mean two or more rows have the same data in these columns.
I suppose I'm looking something opposite to DISTINCT clause
You would want...
SELECT nombre, apellido_paterno, apellido_materno
FROM dbo.personas
GROUP BY nombre, apellido_paterno, apellido_materno
HAVING COUNT(*) > 1
If you want to look at the actual rows, then use that as an inner query and join onto it. So, something like
SELECT *
FROM personas pOuter INNER JOIN
(SELECT nombre, apellido_paterno, apellido_materno
FROM dbo.personas
GROUP BY nombre, apellido_paterno, apellido_materno
HAVING COUNT(*) > 1) pInner
ON pInner.nombre = pOuter.nombre
AND pInner.apellido_paterno = pOuter.apellido_paterno
AND pInner.apellido_materno = pOuter.apellido_materno
;WITH x AS
(
SELECT id_personas, rn = ROW_NUMBER() OVER
(
PARTITION BY nombre, apellido_paterno, apellido_materno
ORDER BY id_personas
)
FROM dbo.personas
)
SELECT <col list>
FROM dbo.personas AS p
WHERE EXISTS
(
SELECT 1 FROM x
WHERE x.id_personas = p.id_personas
AND x.rn > 1
);