How to get the rows position numbers of a table result - tsql

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

Related

Change column value after left join SQL

I have the following statement:
select distinct x_order.code , x_order.status , x_order.project , project.active , project.code as projectcode
from project
left join x_order on x_order.project = project.code
where status = 'B' and active = 0
Which gives me a nice table with all the records I want to change. I now need to change the values in the 'status' column from B to D in this table. How can I do that?
I tried UPDATE, but to no success.
Not sure of the exact table structures you're using, but would a CTE work for you like this...
;WITH CTE
AS (
select distinct x_order.code as ordercode , x_order.status , x_order.project , project.active , project.code as projectcode
from project
left join x_order on x_order.project = project.code
where status = 'B' and active = 0
)
UPDATE X
SET [status] = 'D'
FROM x_order X
JOIN CTE C
ON X.code = C.ordercode

SQL - Rank or Row_Number not bringing back desired data

I'm writing a query that will bring me back either row or rank '1'. When I run the query with the 'where rank or row clause equals 1', no data returns for those columns but if I take out the 'where rank or row clause' the data populates. Can someone tell me why the where clause is causing no data to return?
LEFT OUTER JOIN
(SELECT DISTINCT CLMED.SIMPLE_GENERIC_C
, MEDINFO.MEDICATION_ID as [CYTOTEC]
,FMED.PAT_ENC_CSN_ID
, FMED.HOSP_ADMSN_DATE
-- , MIN(FMED.TAKEN_DATETIME) over (Partition by FMED.PAT_ENC_CSN_ID,
MEDINFO.MEDICATION_ID ) as 'FIRST DOSE'
, MIN(FMED.TAKEN_DATETIME) over (Partition by FMED.PAT_ENC_CSN_ID, CLMED.SIMPLE_GENERIC_C
) AS 'FIRST DOSE'
, RANK() over (Partition by FMED.PAT_ENC_CSN_ID, CLMED.SIMPLE_GENERIC_C order by
FMED.TAKEN_DATETIME DESC) 'CYTOTEC_RANK'
, ROW_NUMBER() over (Partition by FMED.PAT_ENC_CSN_ID, MEDINFO.MEDICATION_ID order by
FMED.TAKEN_DATETIME) AS 'CYTOTEC_ROW'
, FMED.DISPLAY_NAME
, FMED.ORDER_MED_ID
, ORDMED.DESCRIPTION
, ZCGEN.NAME
FROM MED_ADMIN FMED
LEFT JOIN MEDINFO MEDINFO ON FMED.ORDER_MED_ID = MEDINFO.ORDER_MED_ID
LEFT JOIN MED ORDMED ON FMED.ORDER_MED_ID = ORDMED.ORDER_MED_ID
LEFT JOIN MEDICATION CLMED ON MEDINFO.MEDICATION_ID = CLMED.MEDICATION_ID
LEFT JOIN GENERIC ZCGEN ON CLMED.SIMPLE_GENERIC_C = ZCGEN.SIMPLE_GENERIC_C
WHERE ZCGEN.NAME = 'miSOPROStol'
AND 'CYTOTEC_RANK' = 1
) AS [CYT] ON CYT.PAT_ENC_CSN_ID = VITALS.PAT_ENC_CSN_ID

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.

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

combine two sql sets of results while using TOP

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