Can't using alias into GROUP BY clause - sql

I have this join into large query
LEFT JOIN --RIVA MICRO
(SELECT
TT.DATAAREAID, TT.VOUCHER,MA.MAINACCOUNTID AS AD,
SUM(TT.TAXBASEAMOUNT) AS TAXBASEAMOUNT,
SUM(TT.TAXAMOUNT) AS TAXAMOUNT
FROM
TAXTRANS TT
INNER MERGE JOIN
TAXTRANSDETAIL_BE MA ON TT.RECID = MA.RECID
WHERE
TT.TRANSDATE <= #FECHA AND ("+#Codigo_RIVA+")
GROUP BY
TT.DATAAREAID, TT.VOUCHER, MA.MAINACCOUNTID) AS RIVA2 ON Asiento.Asiento = RIVA2.VOUCHER
AND Asiento.Cuenta = RIVA2.AD
AND Asiento.Empresa = RIVA2.DATAAREAID
It works correctly but now I implement a temporary table, so my query is like:
LEFT JOIN
(SELECT
DATAAREAID, VOUCHER, MAINACCOUNTID,
SUM(TAXBASEAMOUNT) AS TAXBASEAMOUNT, SUM(TAXAMOUNT)
FROM
##TTM TT
WHERE
(TT.TAXCODE LIKE 'RIVA11DPT' OR TT.TAXCODE LIKE 'RIVA16DPT'
OR TT.TAXCODE LIKE 'RIVA16T')
GROUP BY
TT.TAXAMOUNT, TT.TAXBASEAMOUNT, TT.TAXCODE, TT.DATAAREAID,
TT.VOUCHER, TT.MAINACCOUNTID) AS RIVA2 ON Asiento.Asiento = RIVA2.VOUCHER
AND Asiento.Cuenta = RIVA2.MAINACCOUNTID
AND Asiento.Empresa = RIVA2.DATAAREAID
But now problem is into GROUP BY CLAUSE, I´m getting into alias AS RIVA2
Incorrect syntax near the keyword 'AS'.
Someone knows why it occurs?. Regards

I think you intend:
LEFT JOIN
(SELECT TT.DATAAREAID, TT.VOUCHER, TT.MAINACCOUNTID,
SUM(TT.TAXBASEAMOUNT) AS TAXBASEAMOUNT, SUM(TT.TAXAMOUNT)
FROM ##TTM TT
WHERE TT.TAXCODE IN ('RIVA11DPT', 'RIVA16DPT', 'RIVA16T')
GROUP BY TT.DATAAREAID, TT.VOUCHER, TT.MAINACCOUNTID
) RIVA2
ON Asiento.Asiento = RIVA2.VOUCHER AND
Asiento.Cuenta = RIVA2.MAINACCOUNTID AND
Asiento.Empresa = RIVA2.DATAAREAID
Notes:
You only need to aggregate by the unaggregated columns in the GROUP BY.
It is well known that you cannot use column aliases defined in a SELECT in most other clauses associated with that SELECT.
IN is much simpler than a collection of OR clauses.
You should give SUM(TT.TAXAMOUNT) a name.

Related

SQL Multiple inner joins with max() for latest recorded entry

Attempting to build SQL with INNER JOIN's. The INNER JOIN's work ok, now I need to add the MAX() function for limiting the rows to just most recent. Added this INNER JOIN client_diagnosis_record ON SELECT cr.PATID, cr.date_of_diagnosis, cr.most_recent_diagnosis...
Received this SQL code error, need some help, I'm sure it a simple oversight but my eyes are getting dim from looking so long...
Syntax error: [SQLCODE: <-4>:
SQLCODE: <-4>:<A term expected, beginning with one of the following: identifier, constant, aggregate, %ALPHAUP, %EXACT, %MVR, %SQLSTRING, %
[%msg: < The SELECT list of the subquery
SELECT pd.patient_name,
cr.PATID,
cr.date_of_diagnosis,
cr.EPISODE_NUMBER,
ce.diagnosing_clinician_value,
ce.data_entry_user_name,
most_recent_diagnosis
FROM client_diagnosis_record cr
INNER JOIN patient_current_demographics pd ON cr.patid = pd.patid
INNER JOIN client_diagnosis_entry ce ON ce.patid = pd.patid
AND cr.ID = ce.DiagnosisRecord
INNER JOIN client_diagnosis_record ON (SELECT cr.PATID,
cr.date_of_diagnosis,
cr.most_recent_diagnosis
FROM ( SELECT patid,
date_of_diagnosis,
MAX(ID) AS most_recent_diagnosis
FROM client_diagnosis_record) cr
INNER JOIN RADplus_users ru ON ru.staff_member_id = ce.diagnosing_clinician_code
WHERE cr.PATID <> '1'
AND ce.diagnosis_status_value ='Active'
AND (ru.user_description LIKE '%SOA' OR ru.user_description LIKE '%OA')
GROUP BY cr.PATID
I tried to re-format you query and it seems your query syntax is not correct. You may try below query -
SELECT pd.patient_name,
cr.PATID,
cr.date_of_diagnosis,
cr.EPISODE_NUMBER,
ce.diagnosing_clinician_value,
ce.data_entry_user_name,
most_recent_diagnosis
FROM client_diagnosis_record cr
INNER JOIN (SELECT patid,
date_of_diagnosis,
MAX(ID) AS most_recent_diagnosis
FROM client_diagnosis_record
GROUP BY patid,
date_of_diagnosis) cr2 ON cr.PATID = cr2.PATID
AND cr.date_of_diagnosis = cr2.date_of_diagnosis
AND cr.ID = cr2.most_recent_diagnosis
INNER JOIN patient_current_demographics pd ON cr.patid = pd.patid
INNER JOIN client_diagnosis_entry ce ON ce.patid = pd.patid
AND cr.ID = ce.DiagnosisRecord
INNER JOIN RADplus_users ru ON ru.staff_member_id = ce.diagnosing_clinician_code
WHERE cr.PATID <> '1'
AND ce.diagnosis_status_value ='Active'
AND (ru.user_description LIKE '%SOA' OR ru.user_description LIKE '%OA')
GROUP BY cr.PATID

Subquery SQL DB2

I am trying to create a subquery (for a particular column) inside my base query. the code is as follows.
SELECT z.po_id,
max
(
select etcdc.ship_evnt_tms
FROM covinfos.shipment_event etcdc
WHERE etcdc.ship_evnt_cd = '9P'
AND etcdc.ship_id=scdc.ship_id
ORDER BY etcdc.updt_job_tms desc
FETCH first ROW only) AS llp_estimated_delivery_cdc
FROM covinfos.ibm_plant_order z
LEFT JOIN covinfos.ipo_line_to_case a
ON z.po_id = a.po_id
LEFT JOIN covinfos.shipment scdc
ON (
a.ship_id = scdc.ship_id
AND a.ship_to_loc_code = scdc.ship_to_loc_code
AND scdc.loc_type = 'CDC')
GROUP BY z.po_id
There seems to be some kind of typo somewhere based on the error message that pops up when I try to run the code.
BIC00004. DAL01008. An error occurred while accessing the database.
ILLEGAL SYMBOL ".". SOME SYMBOLS THAT MIGHT BE LEGAL ARE: , ). SQLCODE=-104,
SQLSTATE=42601, DRIVER=3.62.56; THE CURSOR SQL_CURLH200C1 IS NOT IN A
PREPARED STATE. SQLCODE=-514, SQLSTATE=26501, DRIVER=3.62.56
However, at plain sight or at least my sight, there is nothing that spots the misstake. Furthermore, running the subselect in a blank sheet (outside the base query, new one) it does correctly.
Thanks
You would probably be best to remove the co-related sub-select, and just join to a plain sub-select. E.g.
SELECT z.po_id,
max(ship_evnt_tms) AS llp_estimated_delivery_cdc
FROM covinfos.ibm_plant_order z
LEFT JOIN covinfos.ipo_line_to_case a
ON z.po_id = a.po_id
LEFT JOIN covinfos.shipment scdc
ON a.ship_id = scdc.ship_id
AND a.ship_to_loc_code = scdc.ship_to_loc_code
AND scdc.loc_type = 'CDC'
LEFT JOIN
( select ship_id
, ship_evnt_tms
FROM
( select ship_id
, ship_evnt_tms
, row_number() over(partition by ship_id order by updt_job_tms desc) as RN
FROM covinfos.shipment_event
WHERE ship_evnt_cd = '9P'
) s
WHERE RN = 1
) AS etcdc
ON etcdc.ship_id=scdc.ship_id
GROUP BY z.po_id
P.S. you could just INNER JOINs unless you want to include po_id's with no ship_evnt_tms
Try adding parentheses around the sub-select. At least this then parses Data Studio using z/OS validation
SELECT z.po_id,
max
((
select etcdc.ship_evnt_tms
FROM covinfos.shipment_event etcdc
WHERE etcdc.ship_evnt_cd = '9P'
AND etcdc.ship_id=scdc.ship_id
ORDER BY etcdc.updt_job_tms desc
FETCH first ROW only)) AS llp_estimated_delivery_cdc
FROM covinfos.ibm_plant_order z
LEFT JOIN covinfos.ipo_line_to_case a
ON z.po_id = a.po_id
LEFT JOIN covinfos.shipment scdc
ON (
a.ship_id = scdc.ship_id
AND a.ship_to_loc_code = scdc.ship_to_loc_code
AND scdc.loc_type = 'CDC')
GROUP BY z.po_id
Still, I'm not sure this is a very nice bit of SQL code.

How can I convert a SQL query with a derived table to HQL?

SELECT *
FROM visitdetails vd
LEFT JOIN
(SELECT MAX(id) AS id, VisitID
FROM claimfilelist GROUP BY VisitID) cf ON cf.visitid = vd.Id
LEFT JOIN claimfilelist cf1 ON cf1.id = cf.id
I have this SQL query. How can I convert it to HQL?
The HQL-documentation says that subqueries are only allowed in SELECT and WHERE. So, my first step is to move the subquery to the WHERE-clause:
SELECT *
FROM visitdetails vd
LEFT JOIN claimfilelist cf ON cf.visitid = vd.id
WHERE cf.id IS NULL OR cf.id = (
SELECT max(cfInner.id)
FROM claimfilelist cfInner
WHERE cfInner.visitId = vd.id
)
Depending on your Hibernate - version you might need to change the joins. I am not sure if the query works, but you could give the approach a try.

select columns from different tables with different data type columns

I want to know how to write a query, which selects specific columns(not common) from 2 different tables and combine them together.
I tried this, but didn't work:
SELECT ii.sequence
FROM Costs ii
WHERE ii.order_ID IN (SELECT book.order_ID
FROM BookInfo ci
WHERE ii.order_ID = ci.order_ID)
UNION
SELECT ft.released_title
FROM FinishedBook ft
WHERE ft.version IN (SELECT ii.iiversion
FROM Costs ii
WHERE ii.iiorder_ID IN (SELECT ci.order_ID
FROM BookInfo ci
WHERE ii.iiorder_ID = ci.order_ID))
ORDER BY sequence;
Isn't this a case of joining these tables and calling Distinct to avoid duplicates?
Try this:
select Distinct a.Sequence, b.RELEASED_TITLE
from IncludedIn a inner join FinishedTrack b
on a.OriginatesFrom = b.IIOriginatesFrom
Inner join CdInfo c on a.IIALBUM_ID = c.ALBUM_ID
Order By a.Sequence
For MSSQL Server, Use Join to get the result.
SELECT I.Sequence, F.Released_Title FROM FinishedTrack AS F
INNER JOIN IncludedIn AS I ON I.ORIGINATESFROM = F.IIORIGINATESFROM
INNER JOIN CdInfo AS A ON A.ALBUM_ID = I.IIALBUM_ID
ORDER BY I.Sequence DESC
You need to use a JOIN instead of a UNION:
SELECT ii.sequence, ft.released_title
FROM IncludedIn ii
INNER JOIN CdInfo ci ON ii.iialbumid = ci.album_id
INNER JOIN FinishedTrack ft on ft.originatesfrom = ii.iioriginatesfrom
ORDER BY ii.sequence;
This query might work for you
SELECT IncludedIn.SEQUENCE, FinishedTrack.RELEASED_TITLE
FROM FinishedTrack
INNER JOIN IncludedIn
ON FinishedTrack.ORIGINATESFROM=IncludedIn.IIORIGINATESFROM and
FinishedTrack.VERSION=IncludedIn.IIVERSION order by FinishedTrack.SEQUENCE;

Subquery with multiple joins involved

Still trying to get used to writing queries and I've ran into a problem.
Select count(region)
where (regionTable.A=1) in
(
select jxn.id, count(jxn.id) as counts, regionTable.A
from jxn inner join
V on jxn.id = V.id inner join
regionTable on v.regionID = regionTable.regionID
group by jxn.id, regionTable.A
)
The inner query gives an ID number in one column, the amount of times they appear in the table, and then a bit attribute if they are in region A. The outer query works but the error I get is incorrect syntax near the keyword IN. Of the inner query, I would like a number of how many of them are in region A
You must specify table name in query before where
Select count(region)
from table
where (regionTable.A=1) in
And you must choose one of them.
where regionTable.A = 1
or
where regionTable.A in (..)
Your query has several syntax errors. Based on your comments, I think there is no need for a subquery and you want this:
select jxn.id, count(jxn.id) as counts, regionTable.A
from jxn inner join
V on jxn.id = V.id inner join
regionTable on v.regionID = regionTable.regionID
where regionTable.A = 1
group by jxn.id, regionTable.A
which can be further simplified to:
select jxn.id, count(jxn.id) as counts
, 1 as A --- you can even omit this line
from jxn inner join
V on jxn.id = V.id inner join
regionTable on v.regionID = regionTable.regionID
where regionTable.A = 1
group by jxn.id
You are getting the error because of this line:
where (regionTable.A=1)
You cannot specify a condition in a where in clause, it should only be column name
Something like this may be what you want:
SELECT COUNT(*)
FROM
(
select jxn.id, count(jxn.id) as counts, regionTable.A
from
jxn inner join
V on jxn.id = V.id inner join
regionTable on v.regionID = regionTable.regionID
group by jxn.id, regionTable.A
) sq
WHERE sq.a = 1