Trying to join two sql statement - sql

I would like to join Query 1 and Query 2 on TripId.
Query 1
SELECT tblTrips.TripId,tblVehicles.VehicleNo
FROM tblTrips INNER JOIN tblVehicles ON tblTrips.VehicleId = tblVehicles.VehicleId
Query 2
;with T1 as (
SELECT tblTrips.TripId, tblTripDeductions.Amount, CONVERT(VARCHAR(400),tblDeductionTypes.DeductionType+' - '+tblTripDeductions.Description+' - '+ CONVERT(VARCHAR(24),tblTripDeductions.Amount)) as DeductionFor
FROM tblTrips INNER JOIN
tblTripDeductions ON tblTrips.TripId = tblTripDeductions.TripId INNER JOIN
tblDeductionTypes ON tblTripDeductions.DeductionId = tblDeductionTypes.DeductionId
)select **T1.TripId**, SUM(T1.Amount) as Amount, stuff((select '#',' ' + CONVERT(varchar(1000),T2.DeductionFor) from T1 AS T2 where T1.TripId = T2.TripId for xml path('')),1,1,'') [Description] from T1
Group by TripId
First query's output is list of TripId and VehicleNo.
Second query's output is list of TripId, Amount and description.
And my desire output is TripId, VehicleNo, amount and description.

The Syntax for WITH (Common Table Expressions) allows you to create multiple CTE's.
Using that you can turn your final part of Query2 in to a CTE (Which I'll name Query2) and your query for Query1 can also be made in to a CTE (which I'll name Query1).
Then, the final SELECT statement can simply join those two CTE's together.
;
WITH
T1 as (
SELECT tblTrips.TripId, tblTripDeductions.Amount, CONVERT(VARCHAR(400),tblDeductionTypes.DeductionType+' - '+tblTripDeductions.Description+' - '+ CONVERT(VARCHAR(24),tblTripDeductions.Amount)) as DeductionFor
FROM tblTrips INNER JOIN
tblTripDeductions ON tblTrips.TripId = tblTripDeductions.TripId INNER JOIN
tblDeductionTypes ON tblTripDeductions.DeductionId = tblDeductionTypes.DeductionId
)
,
Query2 AS (
select **T1.TripId**, SUM(T1.Amount) as Amount, stuff((select '#',' ' + CONVERT(varchar(1000),T2.DeductionFor) from T1 AS T2 where T1.TripId = T2.TripId for xml path('')),1,1,'') [Description] from T1
Group by TripId
)
,
Query1 AS (
<Your Code For Query1>
)
SELECT
*
FROM
Query1
INNER JOIN
Query2
ON Query1.TripID = Query2.TripID
I haven't don't anything to check your queries, as the layout that you have used isn't very readable.

Just merge the queries using CTE (didn't change/review your code, just formatted it for the sake of readability - input was pretty horrible to read)
;WITH T1 AS (
SELECT tblTrips.TripId
, tblTrips.DestinationDistrictId
, tblTrips.VehicleId
, tblTrips.No
, tblVehicles.VehicleNo
, tblTrips.CoachNo
, CONVERT(VARCHAR(24), tblTrips.GoDate, 105) AS GoDate
, tblTrips.GoTime
, CASE WHEN tblTrips.IsCome=1
THEN CONVERT(VARCHAR(24), tblTrips.ComeDate, 105)
ELSE '-'
END AS ComeDate
, CASE WHEN tblTrips.IsCome=1
THEN tblTrips.ComeTime
ELSE '-'
END AS ComeTime
, CASE WHEN tblTrips.IsCome=1
THEN (SD.DistrictName + ' - ' + DD.DistrictName + ' - ' + SD.DistrictName)
ELSE (SD.DistrictName + ' - ' + DD.DistrictName)
END AS Destination
, tblSupervisors.Name AS Supervisor
, tblDrivers.Name AS Driver
, tblTrips.AdvanceAmount
, tblTrips.AdvanceDescription
FROM tblTrips
INNER JOIN tblSupervisors ON tblTrips.SuperVisorId = tblSupervisors.SupervisorId
INNER JOIN tblDrivers ON tblTrips.DriverId = tblDrivers.DriverId
INNER JOIN tblDistricts SD ON tblTrips.StartDistrictId = SD.DistrictId
INNER JOIN tblDistricts DD ON tblTrips.DestinationDistrictId = DD.DistrictId
INNER JOIN tblVehicles ON tblTrips.VehicleId = tblVehicles.VehicleId
)
, Q1 AS (
SELECT T1.TripId
, SUM(T1.Amount) AS Amount
, STUFF((
SELECT '#', ' ' + CONVERT(VARCHAR(MAX), T2.DeductionFor)
FROM T1 AS T2
WHERE T1.TripId = T2.TripId FOR XML PATH(''))
,1,1,'') AS [Description]
FROM T1
GROUP BY TripId
)
, Q2 AS (
SELECT tblTrips.TripId
, tblTripDeductions.Amount
, CONVERT(VARCHAR(400), tblDeductionTypes.DeductionType + ' - ' + tblTripDeductions.Description + ' - ' + CONVERT(VARCHAR(24), tblTripDeductions.Amount)) AS DeductionFor
FROM tblTrips
INNER JOIN tblTripDeductions ON tblTrips.TripId = tblTripDeductions.TripId
INNER JOIN tblDeductionTypes ON tblTripDeductions.DeductionId = tblDeductionTypes.DeductionId
)
SELECT *
FROM Q1
INNER JOIN Q2 ON Q1.TripId = Q2.TripId

Related

Filter based on where condition

I have a query where I am getting data for some tickets.Now I need to put a where condition to get data where timediffsecs <> 0.I am unable to get the correct place to put where conditon..
Below is my code .Please help
WITH CTE
AS
(
SELECT cr.ref_num as 'TicketNumber',
isnull(requestor.last_name,'') + ', ' + isnull(requestor.first_name,'') as 'Requestor'
,ISNULL(cnt.last_name, '') + ', ' + ISNULL(cnt.first_name,'') as 'Created By'
,isnull(aeu.last_name,'') + ', ' + isnull(aeu.first_name,'') as 'Affected End User',
isnull(logagent.last_name,'') + ', ' + isnull(logagent.first_name,'') as 'Reported By'
,dbo.ConvertUnixTime (cr.open_date) as 'Open Date'
,dbo.ConvertUnixTime (cr.last_mod_dt) as 'Last Modified Date'
,dbo.ConvertUnixTime (cr.resolve_date) as 'Resolve Date'
,dbo.ConvertUnixTime (cr.close_date) as 'Close Date'
,dbo.ConvertUnixTime (act.time_stamp) as 'systime',
cr.summary as 'Summary'
,convert(varchar(max),cr.[description]) as 'Description'
,act.[action_desc] as 'System Description'
,acttype.sym as 'Activity Type'
,act.time_spent as 'Time Spent',
ROW_NUMBER() OVER(PARTITION BY cr.ref_num ORDER BY dbo.ConvertUnixTime (act.time_stamp)) RN
-- ROW_NUMBER() OVER(ORDER BY dbo.ConvertUnixTime (act.time_stamp) ) RN
-- ROW_NUMBER generated based on ORDER BY Time DESC
-- You can also add case_id or any other column to generate
--ROW_NUMBER so that the time differences can be calculate
--based on other dimension.
from call_req cr with (nolock)
LEFT OUTER JOIN ca_contact requestor with (nolock) on cr.requested_by = requestor.Contact_uuid
LEFT OUTER JOIN ca_contact aeu with (nolock) on cr.customer = aeu.Contact_uuid
LEFT OUTER JOIN ca_contact logagent with (nolock) on cr.log_agent = logagent.Contact_uuid
INNER JOIN act_log act with (nolock) on cr.persid = act.call_req_id
INNER JOIN ca_contact cnt with (nolock) on act.analyst = cnt.contact_uuid
INNER JOIN act_type acttype with (nolock) on act.[type] = acttype.code
where cr.ref_num in ('23035883',
'23038276')
)
SELECT *,
CASE
WHEN A.RN = 3 THEN
DATEDIFF(
SECOND,
(SELECT systime FROM CTE WHERE RN = 2 AND TicketNumber= A.TicketNumber),
(SELECT systime FROM CTE WHERE RN = 3 AND TicketNumber= A.TicketNumber)
-- By setting RN = 3 and 2, I am calculating
-- Time differences between ROW 3 and 2
-- You can set it to any Row number as per your requirement
)
ELSE 0
END as timediffsecs
FROM CTE A
You just need to nest the current SELECT in a subquery:
WITH cte
....
SELECT *
FROM (
YourCurrentSelect
) q
WHERE q.timediffsecs <> 0

(Group By) & (FOR XML PATH) & JOIN

Is there any other approch rather than saving the result of joining (the Table #VT & TableA ) in one Table variable and then from there make the Grouping
select ID ,
STUFF (( select distinct ' / ' + TA.Reason
from #VT
where ( ID = VT.ID )
for xml path(''),TYPE).value('(./text())[1]','VARCHAR(MAX)') ,1,2,'' ) as XXX
from #VT as VT
join TableA as TA on ( TA.ID = VT.ID)
group by ID
I get this Error
Column 'TableA.Reason' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
I would go with DISTINCT instead of GROUP BY :
SELECT DISTINCT ID,
STUFF (( SELECT DISTINCT ' / ' + ta.Reason
FROM TableA ta
WHERE vt.ID = ta.ID
FOR XML PATH (''),TYPE).VALUE('(./text())[1]','VARCHAR(MAX)'
), 1, 2, ''
) AS XXX
FROM #VT vt;
I think you have the tables in the wrong place. Does this work?
select ID ,
stuff(( select distinct ' / ' + TA.Reason
from TableA TA
where vt.ID = ta.ID
for xml path(''), TYPE
).value('(./text()) [1]', 'VARCHAR(MAX)') , 1, 2, ''
) as XXX
from #VT vt ;

SQL Moving SUBSTRING select into INNER JOIN

I have this query
SELECT ID,
SUBSTRING(( SELECT DISTINCT ',' + CONVERT(varchar(10), CC.CompanyId)
FROM Company CC
INNER JOIN CompanyProducts NP2
ON CC.CompanyId = NP2.CompanyId
WHERE NP.CompanyProducts Id = NP2.PrimaryCompanyProducts Id
AND NP2.CompanyProducts Id <> NP2.CompanyProducts Id
FOR XML PATH('')),2,200000) AS CompanyIdList
FROM CompanyProducts NP
I would like to add the SELECT into an INNER JOIN which I will add to my select to check if the return is null or zero
it will be something like this
SELECT ID,
SUBSTRING(( SELECT DISTINCT ',' + CONVERT(varchar(10), CC.CompanyId)
FROM Company CC
INNER JOIN CompanyProducts NP2
ON CC.CompanyId = NP2.CompanyId
WHERE NP.CompanyProducts Id = NP2.PrimaryCompanyProducts Id
AND NP2.CompanyProducts Id <> NP2.CompanyProducts Id
FOR XML PATH('')),2,200000) AS CompanyIdList,
CompanyIdCount --this will be null or a real value
FROM cmp.CompanyProducts NP
INNER JOIN(SELECT DISTINCT A.CompanyProductsId,
(SELECT DISTINCT ',' + CONVERT(varchar(10), CC.CompanyId)
FROM Company CC
INNER JOIN CompanyProducts NP2
ON CC.CompanyId = NP2.CompanyId
WHERE NP.CompanyProducts Id = NP2.PrimaryCompanyProducts Id
AND NP2.CompanyProducts Id <> NP2.CompanyProducts Id ) AS CompanyIdCount
FROM cmp.CompanyProducts A
)E ON NP.CompanyNotificationId = E.CompanyNotificationId
How can I get the inner JOIN to incident null for no records or 1 record or more? THanks

SQL Group By issues with derived table

I'm attempting to create a table of all the latest payments made for an employee. The original table has all the payments made to an employee since they started. I created a derived table to give me only the records with the latest date in them.
I do still have some duplicates where the payment date is the same, in this case I want to add these payment together so they appear on one row instead.
Below is my working code;
SELECT T1.EmployeeCode
, T2.Staff_Number
, T2.Firstname + ' ' + T2.Surname AS Name
, T1.PaymentDate
, T1.p1
, T1.p2
, T1.p3
FROM DB1.dbo.PARTIFPSNI AS T1
--This section is supposed to return only the latest date
INNER JOIN (
SELECT EmployeeCode, MAX(PaymentDate) as MaxDate
FROM DB1.dbo.PARTIFPSNI
GROUP BY EmployeeCode
) T1A ON T1.EmployeeCode = T1A.EmployeeCode and T1.PaymentDate = T1A.MaxDate
LEFT JOIN DB2.dbo.Personnel_Records AS T2 ON (T1.EmployeeCode = T2.Staff_Number)
This returns the below;
I seem to have issues summing together p1, p2 & p3. I think this because I am trying to use the GROUP BY function twice.
SELECT T1.EmployeeCode ,
T2.Staff_Number ,
T2.Firstname + ' ' + T2.Surname AS Name ,
T1.PaymentDate ,
SUM(T1.p1) ,
SUM(T1.p2) ,
SUM(T1.p3)
FROM DB1.dbo.PARTIFPSNI AS T1
INNER JOIN ( SELECT EmployeeCode ,
MAX(PaymentDate) AS MaxDate
FROM DB1.dbo.PARTIFPSNI
GROUP BY EmployeeCode
) T1A ON T1.EmployeeCode = T1A.EmployeeCode
AND T1.PaymentDate = T1A.MaxDate
LEFT JOIN DB2.dbo.Personnel_Records AS T2 ON ( T1.EmployeeCode = T2.Staff_Number )
GROUP BY T1.EmployeeCode ,
T2.Staff_Number ,
T2.Firstname + ' ' + T2.Surname ,
T1.PaymentDate

Single Line separated records in SQL SERVER Query result

I had a query that returned multiple rows from a table. Then I converted that query to this one:
;with mycte as
(select s.FirstName + ' ' + s.LastName as Name from ClientStaff cs
left outer join Staff s on s.Id = cs.StaffId
left outer join GeneralStatus gs on gs.Id = s.StatusId
where cs.ClientId = #clientId and gs.Name = 'Active')
select #staff = (select distinct staff = REPLACE(REPLACE(REPLACE((select Name AS [data()] FROM mycte a
order by a.Name for xml path),'</row><row>',', '),'</row>',''),'<row>','') from mycte b)
It returns those rows in a single comma-separated row.
Now I don't want comma-separated values, instead I want single-line-separated values.
Can anyone tell me if it is possible or not?
Thanks in advance.
declare #staff varchar(max)
;with mycte as
(
select distinct s.FirstName + ' ' + s.LastName as Name
from ClientStaff cs
left outer join Staff s on
s.Id = cs.StaffId
left outer join GeneralStatus gs on
gs.Id = s.StatusId
where cs.ClientId = #clientId and gs.Name = 'Active'
)
select #staff = isnull(#staff + char(13), '') + Name
from mycte b
print #staff