SQL - Dates equal from two columns - sql

I have this query and would like to see the dates only where effective_date from one table = renewal_date from the other table.
SELECT
facets_re_group.prospect_nbr, rmr_run_status, insert_date, renewal_date,
package_item_cd, quote_type, effective_date, quote_expiration_ind,
mhs_lob_code
FROM
facets_re_group
INNER JOIN
facets_re_cur_package ON facets_re_cur_package.prospect_nbr = facets_re_group.prospect_nbr
JOIN
qo_quote ON qo_quote.prospect_nbr = facets_re_group.prospect_nbr
WHERE
insert_date >= to_date('01/01/2020','mm/dd/yyyy')
AND package_item_cd = 'HRA'
AND quote_expiration_ind IS NULL
AND mhs_lob_code NOT IN 'DTL1'
AND mhs_lob_code NOT IN 'DTL2'
AND mhs_lob_code NOT IN 'VIS1'

Related

Error getting the amount grouped by name and account number SQL Server

I have an issue on my SQL query. I tried doing two ways
With the first query I got the right amount but I lose some name descriptions
With the second I got every name descriptions but I got a lower amount.
Context: I want to get the revenue gotten between two dates.
I need the following columns from tables
Table reciboDet I need the columns CtaIngreso, ValorUnitReciboDet
Table CuentaIngreso_A the column nombrectaingreso, ctaingreso (only to create the join)
Table Recibo the columns FechaRecibo and ReciboAnulado
To get the right name descriptions I need to verify the receipt year that was in the table AvpgEnc, but when I do that a lose the amount.
First query
SELECT
ReciboDet.CtaIngreso
, SUM(ReciboDet.ValorUnitReciboDet) AS Total
, CuentaIngreso_A.NombreCtaIngreso
FROM
ReciboDet
INNER JOIN CuentaIngreso_A
ON ReciboDet.CtaIngreso = CuentaIngreso_A.CtaIngreso
WHERE
(ReciboDet.NumRecibo IN
(SELECT NumRecibo
FROM Recibo
WHERE (FechaRecibo BETWEEN '01/10/2020' AND '31/10/2020')
AND (ReciboAnulado = 0)
AND (CuentaIngreso_A.Anio = DATEPART(year, FechaRecibo))
)
)
GROUP BY
ReciboDet.CtaIngreso
, CuentaIngreso_A.NombreCtaIngreso
ORDER BY
CuentaIngreso_A.NombreCtaIngreso
Second query
SELECT
ReciboDet.CtaIngreso [cuenta],
sum(ReciboDet.ValorUnitReciboDet) [monto],
CuentaIngreso_A.NombreCtaIngreso [descripcion]
FROM
ReciboDet
inner join avpgenc
on ReciboDet.NumFactura = AvPgEnc.NumAvPg
inner join CuentaIngreso_A
on ReciboDet.CtaIngreso = CuentaIngreso_A.CtaIngreso
WHERE
(ReciboDet.NumRecibo IN
(SELECT NumRecibo
FROM Recibo
WHERE (FechaRecibo BETWEEN '01/10/2020' AND '31/10/2020')
AND (ReciboAnulado = 0)
)
AND (year(AvPgEnc.FechaVenceAvPg) = CuentaIngreso_A.Anio)
)
GROUP BY
ReciboDet.CtaIngreso
, CuentaIngreso_A.NombreCtaIngreso
ORDER BY
ReciboDet.CtaIngreso

Teradata SQL CASE Statement with multiple conditions

I have the below SQL query -
select distinct HospitalAcctID,
AdmitDate,
DischargeDate,
PatMRN,
Pat_id,
ICD,
MedCenter,
(case when SeqCount =1 and AdmitDate > '06/01/2013' and AdmitDate < '06/01/2018' then 1 else null end ) Firstdiag
from
(
select distinct acct.HSP_ACCOUNT_ID as HospitalAcctID,
cast(acct.ADM_DATE_TIME as date format 'mm/dd/yyyy') as AdmitDate,
cast(acct.DISCH_DATE_TIME as date format 'mm/dd/yyyy') as DischargeDate,
pat.pat_mrn_id as PatMRN,
pat.pat_id as Pat_id,
REF_BILL_CODE as ICD,
grp7.NAME AS MedCenter,
row_number() over (partition by PatMRN order by AdmitDate) as SeqCount
from acct
inner join pat on pat.pat_id = acct.pat_id
inner join hspenc on hspenc.CSN_ID = acct.CSN_ID
inner join dx on acct.ACCOUNT_ID = dx.ACCOUNT_ID and line = 1
inner join edg on dx.DX_ID = edg.DX_ID
inner join loc on loc.LOC_ID = acct.LOC_ID
inner join grp7 ON loc.RPT_GRP_SEVEN = grp7.RPT_GRP_SEVEN
where
grp7.NAME = 'SMC AREA'
and ADMIT_CONF_STAT_C in ('1','4')
and (edg. REF_BILL_CODE in ('431',
'431')
)
and ADT_PAT_CLASS_C in ('1204','12113')
order by AdmitDate;
)Admit
But I am getting the below syntax error -
Syntax error, expected something like an 'EXCEPT' keyword, 'UNION' Keyword or a 'MINUS' keyword between 'AdmitDate' and ','
In the outer select statement, I am trying to get the min (first ) date when the was first diagnosed. I also want to get only the patients who were diagnosed between 6/2013 to 6/2018 which is why I have the CASE statement. But the CASE statement is giving me error.
As #BarbarosÖzhan already wrote, remove the last line order by AdmitDate; in the Derived Table.
But there's no need for ROW_NUMBER:
select distinct acct.HSP_ACCOUNT_ID as HospitalAcctID,
cast(acct.ADM_DATE_TIME as date format 'mm/dd/yyyy') as AdmitDate,
cast(acct.DISCH_DATE_TIME as date format 'mm/dd/yyyy') as DischargeDate,
pat.pat_mrn_id as PatMRN,
pat.pat_id as Pat_id,
REF_BILL_CODE as ICD,
grp7.NAME AS MedCenter,
case when -- current rows is first row
min(AdmitDate)
over (partition by PatMRN) = AdminDate
-- current row within date range
and AdminDate >= DATE '2013-06-01' and AdmitDate < DATE '2018-06-01'
then 1
else null
end as Firstdiag
from acct
inner join pat on pat.pat_id = acct.pat_id
inner join hspenc on hspenc.CSN_ID = acct.CSN_ID
inner join dx on acct.ACCOUNT_ID = dx.ACCOUNT_ID and line = 1
inner join edg on dx.DX_ID = edg.DX_ID
inner join loc on loc.LOC_ID = acct.LOC_ID
inner join grp7 ON loc.RPT_GRP_SEVEN = grp7.RPT_GRP_SEVEN
where
grp7.NAME = 'SMC AREA'
and ADMIT_CONF_STAT_C in ('1','4')
and (edg. REF_BILL_CODE in ('431',
'431')
)
and ADT_PAT_CLASS_C in ('1204','12113')
order by AdmitDate;
I also switched to a Standard SQL date literal DATE '2013-06-01' instead of '06/01/2013'. There's only one possible format for the former (DATE 'YYYY-MM-DD') while the latter depends on the FORMAT of the base column and might fail when it changes (of course not in your query, because you defined it in the CAST).

Why is SQL doing an inner join where an outer join is needed

I have two tables which I want to "outer" join (and then fetch) using SQL. The exact SQL query (in question) is:
SELECT
LEFT(a.cusip, 6) AS cusip6,
a.date, a.prc, a.ret, a.vol, a.spread, a.shrout,
b.epsf12, (b.seqq-b.pstkq) / b.cshoq AS bps
FROM
crsp.msf a
FULL JOIN
compa.fundq b ON (LEFT(a.cusip, 6) = LEFT(b.cusip, 6)
AND a.date = b.datadate)
WHERE
(b.datadate BETWEEN '2010-01-01' and '2015-12-31')
AND (a.date BETWEEN '2010-01-01' and '2015-12-31')
AND (b.cshoq > 0)
This returns 670'293 rows.
But when I fetch the two datasets separately and (outer) join them through R-merge(), I get 1'182'093 rows. The two separate queries I use are:
SELECT
LEFT(cusip, 6) AS cusip6, date, prc, ret, vol, spread, shrout
FROM
crsp.msf
WHERE
date BETWEEN '2010-01-01' and '2015-12-31'
SELECT
LEFT(cusip, 6) AS cusip6, datadate AS date, epsf12,
(seqq-pstkq)/cshoq AS bps
FROM
compa.fundq
WHERE
datadate BETWEEN '2010-01-01' and '2015-12-31'
AND cshoq > 0
And then I merge (outer join) using:
merge(x = data_1, y = data_2, by.x = c("cusip6", "date"), by.y = c("cusip6", "date"), all = T)
This returns 1'182'093 rows which is correct. So my original (first) SQL query is in fact performing an "inner join" when I explicitly specify an outer join. The below R-merge() returned 670'293 rows re-validating that the fetched data from SQL is indeed an inner join.
merge(x = data_1, y = data_2, by.x = c("cusip6", "date"), by.y = c("cusip6", "date"))
What am I doing wrong with my SQL query?
Because the WHERE clause is applied after the JOINs. At this point there are NULL values (as a result of 'failed' JOINs), and those rows fail the WHERE clause.
If you want an OUTER JOIN and a filter, put the filter in the JOIN or a sub-query.
SELECT
LEFT(a.cusip, 6) AS cusip6,
a.date, a.prc, a.ret, a.vol, a.spread, a.shrout,
b.epsf12, (b.seqq-b.pstkq) / b.cshoq AS bps
FROM
(SELECT * FROM crsp.msf WHERE date BETWEEN '2010-01-01' and '2015-12-31') a
FULL JOIN
(SELECT * FROM compa.fundq WHERE datadate BETWEEN '2010-01-01' and '2015-12-31' AND cshoq > 0) b
ON LEFT(a.cusip, 6) = LEFT(b.cusip, 6)
AND a.date = b.datadate

SQL statement merge two rows into one

In the results of my sql-statement (SQL Server 2016) I would like to combine two rows with the same value in two columns ("study_id" and "study_start") into one row and keep the row with higest value in a third cell ("Id"). If any columns (i.e. "App_id" or "Date_arrival) in the row with higest Id is NULL, then it should take the value from the row with the lowest "Id".
I get the result below:
Id study_id study_start Code Expl Desc Startmonth App_id Date_arrival Efter_op Date_begin
167262 878899 954 4.1 udd.ord Afbrudt feb 86666 21-06-2012 N 17-08-2012
180537 878899 954 1 Afsluttet Afsluttet feb NULL NULL NULL NULL
And I would like to get this result:
Id study_id study_start Code Expl Desc Startmonth App_id Date_arrival Efter_op Date_begin
180537 878899 954 1 Afsluttet Afsluttet feb 86666 21-06-2012 N 17-08-2012
My statement looks like this:
SELECT dbo.PopulationStam_V.ELEV_ID AS id,
dbo.PopulationStam_V.PERS_ID AS study_id,
dbo.STUDIESTARTER.STUDST_ID AS study_start,
dbo.Optagelse_Studiestatus.AFGANGSARSAG AS Code,
dbo.Optagelse_Studiestatus.KORT_BETEGNELSE AS Expl,
ISNULL((CAST(dbo.Optagelse_Studiestatus.Studiestatus AS varchar(20))), 'Indskrevet') AS 'Desc',
dbo.STUDIESTARTER.OPTAG_START_MANED AS Startmonth,
dbo.ANSOGNINGER.ANSOG_ID as App_id,
dbo.ANSOGNINGER.ANKOMSTDATO AS Data_arrival',
dbo.ANSOGNINGER.EFTEROPTAG AS Efter_op,
dbo.ANSOGNINGER.STATUSDATO AS Date_begin
FROM dbo.INSTITUTIONER
INNER JOIN dbo.PopulationStam_V
ON dbo.INSTITUTIONER.INST_ID = dbo.PopulationStam_V.SEMI_ID
LEFT JOIN dbo.ANSOGNINGER
ON dbo.PopulationStam_V.ELEV_ID = dbo.ANSOGNINGER.ELEV_ID
INNER JOIN dbo.STUDIESTARTER
ON dbo.PopulationStam_V.STUDST_ID_OPRINDELIG = dbo.STUDIESTARTER.STUDST_ID
INNER JOIN dbo.UDD_NAVNE_T
ON dbo.PopulationStam_V.UDDA_ID = dbo.UDD_NAVNE_T.UDD_ID
INNER JOIN dbo.UDDANNELSER
ON dbo.UDD_NAVNE_T.UDD_ID = dbo.UDDANNELSER.UDDA_ID
LEFT OUTER JOIN dbo.PERSONER
ON dbo.PopulationStam_V.PERS_ID = dbo.PERSONER.PERS_ID
LEFT OUTER JOIN dbo.POSTNR
ON dbo.PERSONER.PONR_ID = dbo.POSTNR.PONR_ID
LEFT OUTER JOIN dbo.KønAlleElevID_V
ON dbo.PopulationStam_V.ELEV_ID = dbo.KønAlleElevID_V.ELEV_ID
LEFT OUTER JOIN dbo.Optagelse_Studiestatus
ON dbo.PopulationStam_V.AFAR_ID = dbo.Optagelse_Studiestatus.AFAR_ID
LEFT OUTER JOIN dbo.frafaldsmodel_adgangsgrundlag
ON dbo.frafaldsmodel_adgangsgrundlag.ELEV_ID = dbo.PopulationStam_V.ELEV_ID
LEFT OUTER JOIN dbo.Optagelse_prioriteterUFM
ON dbo.Optagelse_prioriteterUFM.cpr = dbo.PopulationStam_V.CPR_NR
AND dbo.Optagelse_prioriteterUFM.Aar = dbo.frafaldsmodel_adgangsgrundlag.optagelsesaar
LEFT OUTER JOIN dbo.frafaldsmodel_stoettetabel_uddannelser AS fsu
ON fsu.id_uddannelse = dbo.UDDANNELSER.UDDA_ID
AND fsu.id_inst = dbo.INSTITUTIONER.INST_ID
AND fsu.uddannelse_aar = dbo.frafaldsmodel_adgangsgrundlag.optagelsesaar
WHERE dbo.STUDIESTARTER.STUDIESTARTSDATO > '2012-03-01 00:00:00.000'
AND (dbo.Optagelse_Studiestatus.AFGANGSARSAG IS NULL
OR dbo.Optagelse_Studiestatus.AFGANGSARSAG NOT LIKE '2.7.4')
AND (dbo.PopulationStam_V.INDSKRIVNINGSFORM = '1100'
OR dbo.PopulationStam_V.INDSKRIVNINGSFORM = '1700')
GROUP BY dbo.PopulationStam_V.ELEV_ID,
dbo.PopulationStam_V.PERS_ID,
dbo.STUDIESTARTER.STUDST_ID,
dbo.Optagelse_Studiestatus.AFGANGSARSAG,
dbo.Optagelse_Studiestatus.KORT_BETEGNELSE,
dbo.STUDIESTARTER.OPTAG_START_MANED,
Studiestatus,
dbo.ANSOGNINGER.ANSOG_ID,
dbo.ANSOGNINGER.ANKOMSTDATO,
dbo.ANSOGNINGER.EFTEROPTAG,
dbo.ANSOGNINGER.STATUSDATO
I really hope somebody out there can help.
Many ways, this will work:
WITH subSource AS (
/* Your query here */
)
SELECT
s1.id,
/* all other columns work like this:
COALESCE(S1.column,s2.column)
for example: */
coalesce(s1.appid,s2.appid) as appid
FROM subSource s1
INNER JOIN subSource s2
ON s1.study_id =s2.study_id
and s1.study_start = s2.study_start
AND s1.id > s2.id
/* I imagine some other clauses might be needed but maybe not */
The rest is copy paste

Subquery returned more than 1 value. My WHERE clause needs to remove SELECT statements

I have a SQL Stored Procedure that is giving issues. I am aware that it is most likely the SELECT statements in the WHERE clause that are returning multiple values. I commented out the WHERE and results were returned.
My question is how do I modify the statement so that I can still filter on those conditions?
Stored Proc code:
SELECT
REPORT_SPOOL.ID,
REPORT_SPOOL.REPORT_SPOOL_TYPE_ID,
REPORT_SPOOL.FUND_ID,
REPORT_SPOOL.PERF_ENTITY_ID,
REPORT_SPOOL.REPORT_GUID,
REPORT_SPOOL.REPORT_TEMPLATE_GUID,
PERF_ENTITY.CODE AS PERF_ENTITY_CODE,
PERF_ENTITY.NAME AS PERF_ENTITY_NAME,
FUND.CODE AS FUND_CODE,
FUND.NAME AS FUND_NAME,
REPORT.CODE AS REPORT_CODE,
REPORT.NAME AS REPORT_NAME,
REPORT_TEMPLATE.CODE AS REPORT_TEMPLATE_CODE,
REPORT_TEMPLATE.NAME AS REPORT_TEMPLATE_NAME,
FUND.ACCOUNTING_START AS START_DATE,
FUND.ACCOUNTING_END AS END_DATE
FROM
PERF_ENTITY
RIGHT OUTER JOIN
REPORT
INNER JOIN
REPORT_SPOOL
ON REPORT.GUID = REPORT_SPOOL.REPORT_GUID
INNER JOIN
REPORT_TEMPLATE
ON REPORT_SPOOL.REPORT_TEMPLATE_GUID = REPORT_TEMPLATE.GUID
ON PERF_ENTITY.ID = REPORT_SPOOL.PERF_ENTITY_ID
LEFT OUTER JOIN
FUND
ON REPORT_SPOOL.FUND_ID = FUND.ID
WHERE
(END_DATE IS NULL OR END_DATE > #REPORT_DATE)
AND
REPORT_SPOOL.FUND_ID = (SELECT FUND_ID FROM FUND_HLD WHERE [DATE] = #REPORT_DATE)
AND
REPORT_SPOOL.FUND_ID = (SELECT FUND_ID FROM FUND_TRD_LINE_VIEW WHERE [DATE] >= (SELECT DATEFROMPARTS(YEAR(#REPORT_DATE),MONTH(#REPORT_DATE),1)) AND [DATE] <= #REPORT_DATE)
Those last 2 SELECTS are the issue
Replace = with in in the sub query:
REPORT_SPOOL.FUND_ID in (SELECT FUND_ID FROM FUND_HLD WHERE [DATE] = #REPORT_DATE)
AND
REPORT_SPOOL.FUND_ID in (SELECT FUND_ID FROM FUND_TRD_LINE_VIEW WHERE [DATE] >= (SELECT DATEFROMPARTS(YEAR(#REPORT_DATE),MONTH(#REPORT_DATE),1)) AND [DATE] <= #REPORT_DATE)