combine two sql sets of results while using TOP - tsql

I have these two queries and I want one set of results combining top 5 results for TP and top 5 results for LP.
I really do not know how to explain this more clearly, I have two sets of results, top 5 for LP and top 5 for TP and I would like to have a set of results Incident_TP, IncidentID_TP, IncidentHappenedDate_TP , IncidentNumber_TP , LossValue_TP , RecoveredValue_TP , TotalLoss_TP , Incident_LP, IncidentID_LP, IncidentHappenedDate_LP , IncidentNumber_LP , LossValue_LP , RecoveredValue_LP , TotalLoss_LP
DECLARE #IncidentFromDate_TP DATE = '2011-1-12'
DECLARE #IncidentToDate_TP DATE = '2012-1-12'
DECLARE #IncidentFromDate_LP DATE = '2010-1-12'
DECLARE #IncidentToDate_LP DATE = '2011-1-12'
SELECT TOP 5
Incident_TP = Incident_TP.IncidentID
, IncidentHappenedDate_TP = Incident_TP.IncidentHappenedDate
, IncidentNumber_TP = Incident_TP.IncidentNumber
, LossValue_TP = Incident_TP.TotalLoss
, RecoveredValue_TP = Incident_TP.TotalRecovered
, TotalLoss_TP = Incident_TP.CostOfIncident
FROM
Incident AS Incident_TP
INNER JOIN Site AS Site_TP ON Incident_TP.SiteID = Site_TP.SiteID
INNER JOIN Region AS Region_TP ON Site_TP.RegionID = Region_TP.RegionID
WHERE
Incident_TP.TotalLoss > 0.00
AND Incident_TP.IncidentHappenedDate BETWEEN #IncidentFromDate_TP AND #IncidentToDate_TP
ORDER BY
TotalLoss_TP DESC
, IncidentHappenedDate_TP DESC
SELECT TOP 5
Incident_LP = Incident_LP.IncidentID
, IncidentHappenedDate_LP = Incident_LP.IncidentHappenedDate
, IncidentNumber_LP = Incident_LP.IncidentNumber
, LossValue_LP = Incident_LP.TotalLoss
, RecoveredValue_LP = Incident_LP.TotalRecovered
, TotalLoss_LP = Incident_LP.CostOfIncident
FROM
Incident AS Incident_LP
INNER JOIN Site ON Incident_LP.SiteID = Site.SiteID
INNER JOIN Region ON Site.RegionID = Region.RegionID
WHERE
Incident_LP.TotalLoss > 0.00
AND Incident_LP.IncidentHappenedDate BETWEEN #IncidentFromDate_LP AND #IncidentToDate_TP
ORDER BY
TotalLoss_LP DESC
, IncidentHappenedDate_LP DESC
Many thanks

As Tim suggests you could union the sets together, For example:
DECLARE #IncidentFromDate_TP DATE = '2011-1-12';
DECLARE #IncidentToDate_TP DATE = '2012-1-12';
DECLARE #IncidentFromDate_LP DATE = '2010-1-12';
DECLARE #IncidentToDate_LP DATE = '2011-1-12';
WITH RawData
AS ( SELECT Incident_TP = Incident_TP.IncidentID ,
IncidentHappenedDate_TP = Incident_TP.IncidentHappenedDate ,
IncidentNumber_TP = Incident_TP.IncidentNumber ,
LossValue_TP = Incident_TP.TotalLoss ,
RecoveredValue_TP = Incident_TP.TotalRecovered ,
TotalLoss_TP = Incident_TP.CostOfIncident
FROM Incident AS Incident_TP
INNER JOIN Site AS Site_TP ON Incident_TP.SiteID = Site_TP.SiteID
INNER JOIN Region AS Region_TP ON Site_TP.RegionID = Region_TP.RegionID
WHERE Incident_TP.TotalLoss > 0.00
),
TopFiveSetA
AS ( SELECT TOP 5
*
FROM RawData
WHERE IncidentHappenedDate_TP BETWEEN #IncidentFromDate_TP
AND #IncidentToDate_TP
ORDER BY TotalLoss_TP DESC ,
IncidentHappenedDate_TP DESC
),
TopFiveSetB
AS ( SELECT TOP 5
*
FROM RawData
WHERE IncidentHappenedDate_TP BETWEEN #IncidentFromDate_LP
AND #IncidentToDate_LP
ORDER BY TotalLoss_TP DESC ,
IncidentHappenedDate_TP DESC
),
Merged
AS ( SELECT *
FROM TopFiveSetA
UNION ALL
SELECT *
FROM TopFiveSetB
)
SELECT *
FROM Merged

Related

N1QL query dropping records after join with a subquery

The Below Query is dropping records when i join 2 N1QL sub queries -
We are using couchbase and using N1QL queries.
Full Query -
select
t3.appName,
t3.uuid_proj as uuid,
t3.description,
t3.env,
t3.productStatus
from
( select
t1.uuid as uuid_proj ,
t1.appName as appName ,
t1.description as description,
t2.env as env,
t2.productStatus as productStatus
from
(
select
api_external.uuid ,
api_external.data.appName ,
api_external.data.description
from `api_external`
where type = 'partnerApp'
and data.companyId = '70a149da27cc425da86cba890bf5b143' )t1
join
(
select
api_external.data.env,
api_external.data.productStatus,
api_external.data.partnerAppId
from
`api_external`
where type = 'integration' )t2
on t1.uuid = t2.partnerAppId
) as t3
join (
select t4.uuid as uuid_agg , min(t5.env) as env
from
(select api_external.uuid from `api_external` where type = 'partnerApp' and data.companyId = '70a149da27cc425da86cba890bf5b143' )as t4 join
(select api_external.data.env, api_external.data.partnerAppId from `api_external` where type = 'integration' ) as t5
on t4.uuid = t5.partnerAppId
group by t4.uuid
) as t6
on
t3.uuid_proj = t6.uuid_agg and t3.env = t6.env
As you see it has 2 sub queries -
The below subquery gives 16 records -
select
t1.uuid as uuid_proj
from
(
select
api_external.uuid ,
api_external.data.appName ,
api_external.data.description
from `api_external`
where type = 'partnerApp'
and data.companyId = '70a149da27cc425da86cba890bf5b143' )t1
join
(
select
api_external.data.env,
api_external.data.productStatus,
api_external.data.partnerAppId
from
`api_external`
where type = 'integration' )t2
on t1.uuid = t2.partnerAppId
group by t1.uuid
Also the other subquery also gives 16 records -
select t4.uuid as uuid_agg , min(t5.env) as env
from
(select api_external.uuid from `api_external` where type = 'partnerApp' and data.companyId = '70a149da27cc425da86cba890bf5b143' )as t4 join
(select api_external.data.env, api_external.data.partnerAppId from `api_external` where type = 'integration' ) as t5
on t4.uuid = t5.partnerAppId
group by t4.uuid
By Logic join of both the queries on the same grain UUID must also give 16 records . But it gives only 1 .
What am i doing wrong Please help
The query uses many subqueries and hit the issue.
Try following simplified version
CREATE INDEX ix1 ON api_external(data.companyId, uuid, data.appName, data.description) WHERE type = "partnerApp";
CREATE INDEX ix2 ON api_external(data.partnerAppId, data.env, data.productStatus) WHERE type = "integration";
WITH ct3 AS (SELECT t1.uuid, t1.data.appName, t1.data.description,
t2.data.env, t2.data.productStatus
FROM api_external AS t1
JOIN api_external AS t2 ON t1.uuid = t2.data.partnerAppId
WHERE t1.type = "partnerApp"
AND t1.data.companyId = "70a149da27cc425da86cba890bf5b143"
AND t2.type = "integration"
AND t2.data.partnerAppId IS NOT NULL),
ct6 AS ( SELECT t4.uuid AS uuid_agg , MIN(t5.data.env) AS env
FROM api_external AS t4
JOIN api_external AS t5 ON t4.uuid = t5.data.partnerAppId
WHERE t4.type = "partnerApp"
AND t4.data.companyId = "70a149da27cc425da86cba890bf5b143"
AND t5.type = "integration"
AND t5.data.partnerAppId IS NOT NULL
GROUP BY t4.uuid)
SELECT t3.*
FROM ct3 AS t3
JOIN ct6 AS t6 ON t3.uuid = t6.uuid_agg and t3.env = t6.env;
If same results see following works . After JOIN get all the fields of results of MIN env record each group
SELECT m[1].*
FROM api_external AS t4
JOIN api_external AS t5 ON t4.uuid = t5.data.partnerAppId
WHERE t4.type = "partnerApp"
AND t4.data.companyId = '70a149da27cc425da86cba890bf5b143'
AND t5.type = "integration"
AND t5.data.partnerAppId IS NOT NULL
GROUP BY t4.uuid
LETTING m = MIN([t5.data.env, {t4.uuid, t4.data.appName, t4.data.description,
t5.data.env, t5.data.productStatus}]);

How can I use value from main select in Left Outer Join select - T-SQL

In my below T-SQL Query I need to use EFP_MessageCenter.MessageSender from my main SELECT in the SELECT in my LEFT OUTER JOIN as the value where I have placed <MessageSenderInitials>.
When I set (EFP_MessageCenter_1.MessageSender = EFP_MessageCenter.MessageSender) or (EFP_MessageCenter_1.MessageSender = MessageSenderInitials) I get the error The multi-part identifier "EFP_MessageCenter.MessageSender" could not be bound.
How can I get this to work?
SELECT LOWER(EFP_MessageCenter.MessageSender) AS MessageSenderInitials
, MAX(SenderInfo.FullName) AS SenderFullName
, MAX(SenderInfo.ProfilePicture) AS SenderProfilePicture
, MAX(EFP_MessageCenter_Receiver.UserID) AS ReceiverID
, MAX(EFP_MessageCenter.MessageTimestamp) AS ChangeDate
, COUNT(DisplayCountSelect.Displayed) AS CountNonReadMessages
FROM EFP_MessageCenter_Receiver
INNER JOIN EFP_MessageCenter ON EFP_MessageCenter_Receiver.MessageID = EFP_MessageCenter.id
INNER JOIN EFP_EmploymentUser AS SenderInfo ON EFP_MessageCenter.MessageSender = SenderInfo.Initials
LEFT OUTER JOIN
(SELECT EFP_MessageCenter_Receiver_1.Displayed, EFP_MessageCenter_Receiver_1.UserID, EFP_MessageCenter_1.MessageSender
FROM EFP_MessageCenter AS EFP_MessageCenter_1
INNER JOIN EFP_MessageCenter_Receiver AS EFP_MessageCenter_Receiver_1 ON EFP_MessageCenter_1.id = EFP_MessageCenter_Receiver_1.MessageID
WHERE (EFP_MessageCenter_Receiver_1.Displayed = 0) AND (EFP_MessageCenter_Receiver_1.UserID = 65) AND (EFP_MessageCenter_1.MessageSender = '<MessageSenderInitials>'))
AS DisplayCountSelect
ON DisplayCountSelect.UserID = EFP_MessageCenter_Receiver.UserID
WHERE (EFP_MessageCenter_Receiver.UserID = 65) AND (EFP_MessageCenter.MessageType = 'SPECIFIC')
GROUP BY EFP_MessageCenter.MessageSender
ORDER BY ChangeDate DESC
I've made a slight refactor of your query and changed the outer join to an an outer apply
It's not going to be 100% working I'm sure but should allow you to tweak it and include the correlation you need to.
I suspect you could move the CountNonReadMessages to a count(*) in the apply and possibly remove the aggregation, but that's just a guess.
select Lower(mc.MessageSender) as MessageSenderInitials
, Max(s.FullName) as SenderFullName
, Max(s.ProfilePicture) as SenderProfilePicture
, Max(mr.UserID) as ReceiverID
, Max(mc.MessageTimestamp) as ChangeDate
, Count(s.Displayed) as CountNonReadMessages
from EFP_MessageCenter_Receiver mr
join EFP_MessageCenter mc on mr.MessageID = mc.id
join EFP_EmploymentUser eu on mc.MessageSender = eu.Initials
outer apply (
select mr.Displayed
from EFP_MessageCenter mcx
join EFP_MessageCenter_Receiver mrx on mcx.id = mrx.MessageID
where mrx.Displayed = 0
and mrx.UserId=mr.UserId
and mcx.UserID = 65 /* this should probably be correlated */
and mcx.MessageSender = '<MessageSenderInitials>'
) s
where mr.UserID = 65 and mc.MessageType = 'SPECIFIC'
group by mc.MessageSender
order by ChangeDate desc

count using subqueries in T-sql

The following is my query. I need to get the count of the doctor's visits for each patient in the query. The count isn't right and it's printing 2 rows for each patient.
SELECT
pf.PatientId
, p.Visit
, pf.first
, pf.last
, df.first
, df.last
, doc.reconcile_status
, doc.orderid
, count(p.visit)
FROM [CentricityPS].[dbo].[PatientVisit] p
, [CentricityPS].[dbo].[document] doc
, [CentricityPS].[dbo].[Patientprofile] pf
, [CentricityPS].[dbo].[doctorfacility] df
where df.pvid in ('1507023132004420', '1725527248154950', '1406648461000690')
and p.doctorid = df.DoctorFacilityId
and p.patientprofileid = pf.patientprofileid
and pf.pid = doc.pid
and pf.patientstatusmid = '-900'
and pf.PatientProfileId = p.PatientProfileId
-- and pf.PatientId = '8145'
-- and p.visit >= '2016-01-01' and p.visit <= '2016-07-01'
and not exists (select * from [CentricityPS].[dbo].[PatientVisit] p
where (p.visit > '2013-01-01' and p.visit < = '2016-01-01')
and p.patientprofileid = pf.patientprofileid and pf.patientstatusmid not in (-901) )
and not exists (select * from [CentricityPS].[dbo].[PatientVisit] p
where p.visit <= '2013-01-01'
and p.patientprofileid = pf.patientprofileid and pf.patientstatusmid not in (-901) )
-- and pf.patientid = '100293'
group by df.DoctorFacilityId, pf.PatientId, p.visit, pf.first, pf.last, df.first, df.last, doc.RECONCILE_STATUS, doc.ORDERID, p.PatientProfileId
order by df.doctorfacilityid, pf.patientid, p.visit desc
What am I doing wrong?
Help!!!
You're grouping on too many fields. If you just need the count of doctor's visits for each patient, only SELECT PatientProfile fields along with count(p.visit) and just include the same PatientProfile fields in the GROUP BY.

How to get the rows position numbers of a table result

This is my code
Select #pos = Pos, #ptsReputacion = isnull(AA.PtsReputacion,0)
From
(Select
ROW_NUMBER() OVER (ORDER BY #ptsReputacion DESC) AS Pos
, USUARIO.CodUsuario
, PtsReputacion = (Select isnull(sum(Puntos),0) as Puntos
From USUARIO_RANKING_INTERES
Where USUARIO_RANKING_INTERES.CodUsuario = #codUsuario)
, USUARIO.CantIntentos as Intentos
, USUARIO.CantAciertos as Aciertos
, USUARIO.CantFallos as Fallos
, isnull(USUARIO.PG,0) as PG
, isnull(USUARIO.PE,0) as PE
, isnull(USUARIO.PP,0) as PP
, isnull(USUARIO.TiempoTotal,0) as TiempoTotal
From USUARIO) AA
Where AA.CodUsuario = #codUsuario
But it doesn't works because the Pos field has an other value. For example, it gives 2 instead 1.
I want to know how to get the row position number one by one ordered by a variable (because the field is a subquery).
It looks like you really want to do something like the below. I'm using CTEs because that makes it easier to read.
WITH BaseQuery AS
(
SELECT
U.CodUsuario
, PtsReputacion = (Select isnull(sum(Puntos),0) as Puntos
From USUARIO_RANKING_INTERES
Where USUARIO_RANKING_INTERES.CodUsuario = U.CodUsuario)
, USUARIO.CantIntentos as Intentos
, USUARIO.CantAciertos as Aciertos
, USUARIO.CantFallos as Fallos
, isnull(USUARIO.PG,0) as PG
, isnull(USUARIO.PE,0) as PE
, isnull(USUARIO.PP,0) as PP
, isnull(USUARIO.TiempoTotal,0) as TiempoTotal
FROM USUARIO U
),
RNQuery AS
(
SELECT
*
, ROW_NUMBER() OVER (ORDER BY PtsReputacion DESC) AS Pos
FROM
BaseQuery
)
SELECT
#pos = Pos
, #ptsReputacion = isnull(AA.PtsReputacion,0)
FROM
RNQuery AS AA
WHERE
AA.CodUsuario = #codUsuario

Sub Query Returns More Than 1 Value

I am getting error Sub Query Returns more than 1 value
here is my Query
SELECT d.Description ,s.Version , d.UtiPrefix , d.UTI , d.PrimaryAC , s.ReportingObb , s.ReportingObb , d.LEI , d.LEI_Countp , d.LEI , s.ReportingDeleg ,d.Curr , c.Trade_Party_Domicile ,c.LEI_SGR
, Price =( select Price
From Price
inner join Derivatives
on Derivatives.UTI = Price.UTI)
FROM Derivatives as d
INNER JOIN Settings as s
ON d.LEI_SGR = s.LEI_SGR
INNER JOIN Clients c
ON d.LEI_SGR = c.LEI_SGR
Use a correlated subquery
Price =( select Price From Price p WHERE d.UTI = p.UTI)
I suspect this returns more than one row
( select Price
From Price
inner join Derivatives
on Derivatives.UTI = Price.UTI )
why are you mixing sub queries with joins?
SELECT d.Description ,s.Version , d.UtiPrefix , d.UTI , d.PrimaryAC , s.ReportingObb
, s.ReportingObb , d.LEI , d.LEI_Countp , d.LEI , s.ReportingDeleg ,d.Curr
, c.Trade_Party_Domicile ,c.LEI_SGR
, p.Price
FROM Derivatives as d
INNER JOIN Settings as s
ON d.LEI_SGR = s.LEI_SGR
INNER JOIN Clients c
ON d.LEI_SGR = c.LEI_SGR
INNER JOIN Price p
ON p.UTI = d.UTI