Regarding SQL Distinct clause - sql

I am trying to output the following data with only one row for each location. Right now it shows:
120....
120...
120...
Im trying to get it to sum all the values up into one row for 120, one row for 123, one row for 128, ect. I think this has something to do with DISTINCT clauses but I'm kinda brain fried looking at this...
SELECT ICLOCATION.LOCATION,
ICLOCATION.NAME,
ITEMMAST.ITEM,
ITEMMAST.DESCRIPTION,
ITEMLOC.SOH_QTY,
OnOrder,
AllocQty,
SUM(ITEMLOC.SOH_QTY + t.OnOrder - t.AllocQty) AS NetOnHand
FROM (SELECT ITEMLOC.ITEM,
SUM(ISNULL(ITEMLOC.ONORDER_QTY, 0) + ITEMLOC.INTRANS_QTY + ITEMLOC.WIP_QTY) AS OnOrder,
SUM(ITEMLOC.ALLOC_QTY + ITEMLOC.UNALLOC_QTY + ITEMLOC.BACKORD_QTY + ITEMLOC.IN_PROC_QTY + ITEMLOC.HOLD_QTY) AS AllocQty
FROM ITEMLOC
GROUP BY ITEMLOC.ITEM) t
INNER JOIN ITEMLOC
ON ITEMLOC.ITEM = t.ITEM
INNER JOIN ITEMMAST
ON ITEMLOC.ITEM = ITEMMAST.ITEM
INNER JOIN ICLOCATION
ON ITEMLOC.COMPANY = ICLOCATION.COMPANY
WHERE ( ICLOCATION.LOCATION = '120'
OR ICLOCATION.LOCATION = '123'
OR ICLOCATION.LOCATION = '128'
OR ICLOCATION.LOCATION = '129'
OR ICLOCATION.LOCATION = 'HD41D'
OR ICLOCATION.LOCATION = 'HD21H'
OR ICLOCATION.LOCATION = 'HD91H' )
AND ITEMMAST.ITEM = '0210950'
GROUP BY ITEMMAST.ITEM,
ICLOCATION.LOCATION,
ICLOCATION.NAME,
ITEMMAST.DESCRIPTION,
ITEMLOC.SOH_QTY,
ITEMLOC.ITEM,
OnOrder,
AllocQty
ORDER BY ICLOCATION.LOCATION,
ITEMMAST.ITEM

Pare down your GROUP BYs. It's first going to group by ITEMMAST.ITEM, and then ICLOCATION.LOCATION. Either switch the order or get rid of the ITEM.
Also, unrelated, you may want to clean it up a bit by using the IN operator in your WHERE statement. i.e.
ICLOCATION.LOCATION IN ('120', '123', '128', '129', 'HD41D', 'HD21H', 'HD91H')

Related

I am converting Oracle queries to Standard Bigquery, i am gettting error "IN subquery is not supported inside join predicate."

I have converted oracle query into below standard bq but in last statement(IN subquery). I am getting error:
"IN subquery is not supported inside join predicate."
Please advise how to use IN subquery in bq in the below code
#Last part of the code
INNER JOIN (
SELECT
DISTINCT `domain-rr.oracle_DB_DB.he_project_assoc`.PARENT_ISBN
PARENT_ISBN,
SUM (`domain-rr.DB_RPT.PROJECT_GR_QTY`.GR_QTY) GR_QTY
FROM
`domain-rr.oracle_DB_DB.he_project_assoc`
INNER JOIN
`domain-rr.DB_RPT.PROJECT_GR_QTY`
ON
`domain-rr.oracle_DB_DB.he_project_assoc`.child_ISBN = `domain-
rr.DB_RPT.PROJECT_GR_QTY`.BIC_GCISBN
AND `domain-rr.oracle_DB_DB.he_project_assoc`.BREAK_LABEL <>
'Associated ISBNs'
GROUP BY
`domain-rr.oracle_DB_DB.he_project_assoc`.PARENT_ISBN) xx
ON
yy.PARENT_ISBN = xx.PARENT_ISBN
AND yy.CIRCULATION_INT < xx.GR_QTY
AND yy.PARENT_ISBN IN
( SELECT
DISTINCT _BIC_GCISBN
FROM
`domain-rr.DB_RPT.BIC_GM_AGCPOAODS00_BO_VW`
INNER JOIN
`domain-rr.oracle_DB_boadmin.fiscal_bo`
ON
_BIC_ZC2GRIRIN = 'G'
AND _BIC_ZCLOEKZ = ' '
AND SUBSTR (BOUND_DATE, 1, 6) = `domain-
rr.oracle_DB_boadmin.fiscal_bo`.PRIOR_FISC_YEAR_MONTH )
Can you try like this:
Select * from (
#Last part of the code
INNER JOIN (
SELECT
DISTINCT `pearson-rr.oracle_grdw_grdw.he_project_assoc`.PARENT_ISBN
PARENT_ISBN,
SUM (`pearson-rr.GRDW_RPT.PROJECT_GR_QTY`.GR_QTY) GR_QTY
FROM
`pearson-rr.oracle_grdw_grdw.he_project_assoc`
INNER JOIN
`pearson-rr.GRDW_RPT.PROJECT_GR_QTY`
ON
`pearson-rr.oracle_grdw_grdw.he_project_assoc`.child_ISBN = `pearson-
rr.GRDW_RPT.PROJECT_GR_QTY`.BIC_GCISBN
AND `pearson-rr.oracle_grdw_grdw.he_project_assoc`.BREAK_LABEL <>
'Associated ISBNs'
GROUP BY
`pearson-rr.oracle_grdw_grdw.he_project_assoc`.PARENT_ISBN) xx
ON
yy.PARENT_ISBN = xx.PARENT_ISBN
AND yy.CIRCULATION_INT < xx.GR_QTY
) AA
where AA.PARENT_ISBN IN
( SELECT
DISTINCT _BIC_GCISBN
FROM
`pearson-rr.GRDW_RPT.BIC_GM_AGCPOAODS00_BO_VW`
INNER JOIN
`pearson-rr.oracle_grdw_boadmin.fiscal_bo`
ON
_BIC_ZC2GRIRIN = 'G'
AND _BIC_ZCLOEKZ = ' '
AND SUBSTR (BOUND_DATE, 1, 6) = `pearson-
rr.oracle_grdw_boadmin.fiscal_bo`.PRIOR_FISC_YEAR_MONTH )

Query specific field based on max sequence number

I have a record set where some of the rows are duplicated. In particular, they are duplicated for the last three rows of the record set. Of the entire four rows, the correct result set that I desire would include the first row and the last row. I desire this because for a particular SARAPPD_TERM_CODE_ENTRY, the record needed is the one where the SARAPPD_SEQ_NO value is at its max. So, the first row because for that particular term, the sequence number is maxed at one and the last row because the sequence number is maxed at six. Image and query are below.
select ppd.sarappd_seq_no, ppd.sarappd_term_code_entry, ppd.sarappd_apdc_code,
dap. dap.saradap_term_code_entry,
spri.spriden_id,
t.sgbstdn_astd_code, t.*
from sgbstdn t
left join spriden spri on t.sgbstdn_pidm = spri.spriden_pidm
left join saradap dap on spri.spriden_pidm = dap.saradap_pidm
join sarappd ppd on dap.saradap_pidm = ppd.sarappd_pidm
where t.sgbstdn_astd_code not in ('AS', 'DS', 'WD', 'SU', 'LA')
and t.sgbstdn_stst_code = 'AS'
and spri.spriden_change_ind is null
and spri.spriden_id = '123456789'
and (ppd.sarappd_apdc_code = 25 or ppd.sarappd_apdc_code = 30
or ppd.sarappd_apdc_code =35)
and ppd.sarappd_term_code_entry = dap.saradap_term_code_entry
--where b.sarappd_term_code_entry = ppd.sarappd_term_code_entry)
order by ppd.sarappd_term_code_entry
I believe this is a simple "where this = ( select max() ) type of query but I've been trying some different things and nothing is working. I'm not getting the results I want. So with that said, any help on this would be greatly appreciated. Thanks in advance.
You could use ROW_NUMBER()
;WITH cte
AS
(select
ROW_NUMBER() OVER (PARTITION BY SARAPPD_TERM_CODE_ENTRY ORDER BY SARAPPD_SEQ_NO DESC) AS RN
ppd.sarappd_seq_no,
ppd.sarappd_term_code_entry,
ppd.sarappd_apdc_code,
dap. dap.saradap_term_code_entry,
spri.spriden_id,
t.sgbstdn_astd_code, t.*
from sgbstdn t
left join spriden spri on t.sgbstdn_pidm = spri.spriden_pidm
left join saradap dap on spri.spriden_pidm = dap.saradap_pidm
join sarappd ppd on dap.saradap_pidm = ppd.sarappd_pidm
where t.sgbstdn_astd_code not in ('AS', 'DS', 'WD', 'SU', 'LA')
and t.sgbstdn_stst_code = 'AS'
and spri.spriden_change_ind is null
and spri.spriden_id = '123456789'
and (ppd.sarappd_apdc_code = 25 or ppd.sarappd_apdc_code = 30
or ppd.sarappd_apdc_code =35)
and ppd.sarappd_term_code_entry = dap.saradap_term_code_entry
order by ppd.sarappd_term_code_entry) a
SELECT *
FROM cte WHERE rn = 1

Progress SQL Column cannot be found or is not specified for query

I'm writing SQL against a Progress 10.2B07 database and am getting the following error "Column 'OUTERINVOICEHEADER.MEMBERID' cannot be found or is not specified for query (13865).
Here is the query:
select concat(substring(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6) + '-', OuterInvoiceHeader.sold_to_cust_seq) as MemberID,
sum(OuterInvoiceHeader.net_weight) as TotalInvoicePounds,
sum(OuterInvoiceHeader.net_weight / 2000) as TotalTons,
sum(OuterInvoiceHeader.invoice_amt) as InvoiceAmount,
sum(InvoiceSurcharges.Surcharge) as Surcharges,
sum(OuterInvoiceHeader.invoice_amt - InvoiceSurcharges.Surcharge) as Total,
sum(Returns.qty_received) as PoundsReturned
from AXS.PUB.ivc_header OuterInvoiceHeader
inner join
(select m.invoice_nbr, sum(m.extension) Surcharge from AXS.PUB.ivc_mchgs m
inner join
AXS.PUB.ivc_header h
on h.invoice_nbr = m.invoice_nbr
group by m.invoice_nbr) InvoiceSurcharges
on OuterInvoiceHeader.invoice_nbr = InvoiceSurcharges.invoice_nbr
left outer join
(select concat(substring(ReturnHeader.ship_to_nbr, 1, 6)+'-',InnerInvoiceHeader.sold_to_cust_seq) as ReturnMemberID,
ReturnHeader.invoice_nbr as ReturnInvoiceNum,
qty_received
from AXS.PUB.return_hdr ReturnHeader
inner join
AXS.PUB.ivc_header InnerInvoiceHeader
on ReturnHeader.invoice_nbr = InnerInvoiceHeader.invoice_nbr
inner join AXS.PUB.return_line ReturnLine
on ReturnHeader.claim_nbr = ReturnLine.claim_nbr
where ReturnInvoiceNum = '0001010914'
group by ReturnMemberID, ReturnInvoiceNum, qty_received) Returns
on OuterInvoiceHeader.MemberID = Returns.ReturnMemberID
--on OuterInvoiceHeader.invoice_nbr = Returns.ReturnInvoiceNum
where OuterInvoiceHeader.sold_to_cust_nbr = '000837' and OuterInvoiceHeader.invoice_date between '06/01/2016' and '06/30/2016' and OuterInvoiceHeader.invoice_status = '5804' and OuterInvoiceHeader.invoice_type='5601'
group by MemberID
The problem is in the left join; the commented out on clause "on OuterInvoiceHeader.invoice_nbr = Returns.ReturnInvoiceNum" will work if uncommented. The "on OuterInvoiceHeader.MemberID = Returns.ReturnMemberID" clause gives me the error.
What I don't understand is that both of these reference a column in the top SELECT statement, the only difference is that one is a concatenation and the other is not.
I hope that I just can't see the forest for the trees here and the answer is simple, so if anyone has any suggestions or questions I'm all ears.
try this:
I replaced the references to the alias MemberID to be the actual concatinated columns CONCAT(SUBSTRING(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6)+'-', OuterInvoiceHeader.sold_to_cust_seq)
SELECT CONCAT(SUBSTRING(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6)+'-', OuterInvoiceHeader.sold_to_cust_seq) AS MemberID
, SUM(OuterInvoiceHeader.net_weight) AS TotalInvoicePounds
, SUM(OuterInvoiceHeader.net_weight / 2000) AS TotalTons
, SUM(OuterInvoiceHeader.invoice_amt) AS InvoiceAmount
, SUM(InvoiceSurcharges.Surcharge) AS Surcharges
, SUM(OuterInvoiceHeader.invoice_amt - InvoiceSurcharges.Surcharge) AS Total
, SUM(Returns.qty_received) AS PoundsReturned
FROM AXS.PUB.ivc_header OuterInvoiceHeader
INNER JOIN
(SELECT m.invoice_nbr
, SUM(m.extension) Surcharge
FROM AXS.PUB.ivc_mchgs m
INNER JOIN AXS.PUB.ivc_header h ON h.invoice_nbr = m.invoice_nbr
GROUP BY m.invoice_nbr) InvoiceSurcharges ON OuterInvoiceHeader.invoice_nbr = InvoiceSurcharges.invoice_nbr
LEFT OUTER JOIN
(SELECT CONCAT(SUBSTRING(ReturnHeader.ship_to_nbr, 1, 6)+'-', InnerInvoiceHeader.sold_to_cust_seq) AS ReturnMemberID
, ReturnHeader.invoice_nbr AS ReturnInvoiceNum
, qty_received
FROM AXS.PUB.return_hdr ReturnHeader
INNER JOIN AXS.PUB.ivc_header InnerInvoiceHeader ON ReturnHeader.invoice_nbr = InnerInvoiceHeader.invoice_nbr
INNER JOIN AXS.PUB.return_line ReturnLine ON ReturnHeader.claim_nbr = ReturnLine.claim_nbr
WHERE ReturnInvoiceNum = '0001010914'
GROUP BY ReturnMemberID
, ReturnInvoiceNum
, qty_received) Returns ON CONCAT(SUBSTRING(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6)+'-', OuterInvoiceHeader.sold_to_cust_seq) = Returns.ReturnMemberID
--on OuterInvoiceHeader.invoice_nbr = Returns.ReturnInvoiceNum
WHERE OuterInvoiceHeader.sold_to_cust_nbr = '000837'
AND OuterInvoiceHeader.invoice_date BETWEEN '06/01/2016' AND '06/30/2016'
AND OuterInvoiceHeader.invoice_status = '5804'
AND OuterInvoiceHeader.invoice_type = '5601'
GROUP BY CONCAT(SUBSTRING(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6)+'-', OuterInvoiceHeader.sold_to_cust_seq);
Basically you need to keep in mind the order which SQL statements are executed:
FROM clause
WHERE clause
GROUP BY clause
HAVING clause
SELECT clause
ORDER BY clause
That's a computed column alias and thus the error. You should consider using the entire expression rather like
on concat(substring(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6) + '-', OuterInvoiceHeader.sold_to_cust_seq) = Returns.ReturnMemberID
Instead of on OuterInvoiceHeader.MemberID = Returns.ReturnMemberID. As well, change any other place where you are using the same alias. You can and should use that alias only in a outer query and not in the same query.

Rows to Columns with Row as Column Name Grouping

I have a query which I need to transpose the rows returned into separate columns, but I need the column names returned from the row values, and another field as the value under these columns.
Ultimately this will be going into Excel. I initially thought I could do it with a pivot, but the values field cannot accept text without some work, and there are too many "film right types" to work with. I know the specific rights type currently, but the right descriptions and number of rights may change in the future, so I want it to be as flexible as possible.
I want to group by producer, film and country, with the "Film Right Type" as the columns going across, and the "Availability" as the value for the right type column.
My query as it stands.
Select product_detail.pd_product_code as 'ProductCode',
product_analysis.pa_m_9 as 'Producer',
product_detail.pd_abbv_description as 'Film',
product_detail.pd_commodity_code as 'Country',
variant_analysis.vaa_c_10 as 'Film Right Type',
case when isnull(variant_analysis.vaa_l_1,0) = 0 then 'Non-Exclusive'
Else
case when dateadd(day,datediff(DAY,0,isnull(orders.LastDate,getdate())),0) > dateadd(day,datediff(DAY,0,getdate()),0)
Then 'Available On '+convert(varchar(10),Orders.LastDate, 103)
Else 'Available'
End
end as 'Availability'
From product_detail
join variant_detail on variant_detail.vad_pd_id = product_detail.pd_id
left join variant_analysis on variant_analysis.vaa_vad_id = variant_Detail.vad_id
left join product_analysis on product_analysis.pa_pd_id = product_detail.pd_id
join (select count(variant_detail.vad_id) as CountVariants, variant_Detail.vad_pd_id from variant_Detail group by variant_detail.vad_pd_id) as Variants on Variants.vad_pd_id = product_detail.pd_id
Outer Apply
(select top 1
customer_detail.cd_statement_name as Customer,
order_header_analysis.oha_d_2 as LastDate,
system_order_type.sot_description as OrderType,
order_header.oh_order_number as OrderNo
from order_header
join customer_detail on customer_detail.cd_id = order_header.oh_cd_id
join order_line_item on order_line_item.oli_oh_id = order_header.oh_id
join system_order_type on system_order_type.sot_id = order_header.oh_sot_id
left join order_header_analysis on order_header_analysis.oha_oh_id = order_header.oh_id
where order_header_analysis.oha_d_2 >= getdate()
and order_header.oh_sot_id in (1, 2, 3)
and order_line_item.oli_vad_id = variant_detail.vad_id
ORder By order_header_analysis.oha_d_2 desc) as Orders
where isnull(variant_analysis.vaa_l_2,0) = 0
This is the data I currently get out of it:
This is how I want the end result.
Edit:
I have nearly got this doing what I want after using a pivot.
My below query gives me exactly what I need:
Select *
From(
Select product_detail.pd_product_code as 'ProductCode',
product_analysis.pa_m_9 as 'Producer',
product_detail.pd_abbv_description as 'Film',
product_detail.pd_commodity_code as 'Country',
variant_analysis.vaa_c_10 as 'FilmRightType',
case when isnull(variant_analysis.vaa_l_1,0) = 0 then 'Non-Exclusive'
Else
case when dateadd(day,datediff(DAY,0,isnull(orders.LastDate,getdate())),0) > dateadd(day,datediff(DAY,0,getdate()),0)
Then 'Available On '+convert(varchar(10),Orders.LastDate, 103)
Else 'Available'
End
end as 'Availability'
From product_detail
join variant_detail on variant_detail.vad_pd_id = product_detail.pd_id
left join variant_analysis on variant_analysis.vaa_vad_id = variant_Detail.vad_id
left join product_analysis on product_analysis.pa_pd_id = product_detail.pd_id
join (select count(variant_detail.vad_id) as CountVariants, variant_Detail.vad_pd_id from variant_Detail group by variant_detail.vad_pd_id) as Variants on Variants.vad_pd_id = product_detail.pd_id
Outer Apply
(select top 1
customer_detail.cd_statement_name as Customer,
order_header_analysis.oha_d_2 as LastDate,
system_order_type.sot_description as OrderType,
order_header.oh_order_number as OrderNo
from order_header
join customer_detail on customer_detail.cd_id = order_header.oh_cd_id
join order_line_item on order_line_item.oli_oh_id = order_header.oh_id
join system_order_type on system_order_type.sot_id = order_header.oh_sot_id
left join order_header_analysis on order_header_analysis.oha_oh_id = order_header.oh_id
where order_header_analysis.oha_d_2 >= getdate()
and order_header.oh_sot_id in (1, 2, 3)
and order_line_item.oli_vad_id = variant_detail.vad_id
ORder By order_header_analysis.oha_d_2 desc) as Orders
where isnull(variant_analysis.vaa_l_2,0) = 0
) as FilmVals
pivot
(
max(Availability)
for FilmRightType in (
[Theatrical], [DVD], [Blu ray], [Free TV], [Pay TV], [Video on Demand Catch Up], [Subscription Video on Demand], [Advertising Video on Demand], [TV On Demand Download to Own], [TV On Demand Download to Rent]
)
) piv;
I want to set the list of RightTypes to be dynamic from the DB.
I've created another query using for XML Path and this returns the data in the correct format:
(Select left(RightType.RightTypesList,len(RightType.RightTypesList)-1) From (Select
(Select
DISTINCT
'['+variant_analysis.vaa_c_10+']'+', '
from variant_analysis
where variant_analysis.vaa_c_10 is not null
order by 1
For XML Path ('')) as RightTypesList) as RightType)
But when I put this in place of the hard coded list, I get the following error:
Msg 102, Level 15, State 1, Line 44
Incorrect syntax near '('.
Msg 102, Level 15, State 1, Line 52
Incorrect syntax near ')'.
Try to use PIVOT operator in SQL
Here is an example

Oracle SQL - using the coalesce function

I really can't get my head around the coalesce function ... or if this is even the best way to get the result I'm trying to achieve.
I have three dates in the following script (iv.dated, iv1.dated, dh.actshpdate). When I run the following script the dates are in separate columns (as expected);
select unique li.catnr, li.av_part_no, li.artist||' / '||li.title description, li.cust_catnr pallet_ref,
trunc(iv.dated), trunc(iv1.dated), trunc(dh.actshpdate)
from leos_item li
left join invtran_view_oes iv
on li.av_part_no = iv.part_no
and (iv.transaction = 'NREC' and iv.location_no = ' RETURNS W')
left join invtran_view_oes iv1
on li.av_part_no = iv1.part_no
and (iv1.transaction = 'CORR+' and iv1.remark like 'STOCK FROM SP PALLET%')
left join oes_delsegview od
on od.catnr = li.catnr
and od.prodtyp = li.prodtyp
and od.packtyp = li.packtyp
left join oes_dpos dp
on od.ordnr = dp.ordnr
and od.posnr = dp.posnr
and od.segnr = dp.segnr
left join oes_dhead dh
on dp.dheadnr = dh.dheadnr
where li.cunr = '816900'
and substr(li.catnr,1,5) in ('RGMCD','RGJCD')
and li.item_type = 'FP'
and li.catnr = 'RGJCD221'
What I would like to achieve is one column with all dates in date order.
I tried replacing my dates with ...
trunc(coalesce(iv.dated, iv1.dated, dh.actshpdate)) transaction_date
... but, I lose some of the dates;
How can I achieve the following result?
You could use UNION in the following way -
WITH DATA AS(
<your query goes here>
)
SELECT A, b, c, d, e FROM DATA
UNION
SELECT A,b,c,d,f FROM DATA
UNION
SELECT A,b,c,d,g FROM DATA
where a, b, c, d, e, f, g are the column alias of the select list in your original query. You can give your own column alias in the UNION query.