I've put together this resulting query using Eloquent and Laravel's Query Builder (mixed) and I'd like to remove that "mixed" and build the entire query using Laravel's Query Builder.
How would the following query look like with Laravel's Query Builder?
SELECT id,
name,
clicks_count,
conversions_count,
Round(((100 / clicks_count) * conversions_count), 2) AS conversion_rate,
Cast((cost_integral / clicks_count) AS UNSIGNED) AS cpc_integral,
Cast((Ifnull(revenue_integral, 0) / clicks_count) AS UNSIGNED) AS epc_integral,
Cast(Ifnull(revenue_integral, 0) AS signed) AS revenue_integral,
Cast(Ifnull(cost_integral, 0) AS UNSIGNED) AS cost_integral,
Cast((Ifnull(revenue_integral, 0) - cost_integral) AS signed) AS profit_integral,
Round((CASE
WHEN(Ifnull(revenue_integral, 0) = 0 AND Ifnull(cost_integral, 0) = 0) THEN 0
WHEN(Ifnull(revenue_integral, 0) = 0 AND Ifnull(cost_integral, 0) > 0) THEN -100
WHEN(Ifnull(revenue_integral, 0) > 0 AND Ifnull(cost_integral, 0) = 0) THEN 100
WHEN(Ifnull(revenue_integral, 0) > 0 AND Ifnull(cost_integral, 0) > 0) THEN ((revenue_integral / cost_integral) * 100)
END), 2) AS roi
FROM
(SELECT device_types.*,
(SELECT Count(clicks.id)
FROM clicks
WHERE device_types.id = clicks.device_type_id
AND clicks.created_at BETWEEN "2021-07-06 00:00:00" AND "2021-07-08 23:59:59"
AND clicks.campaign_id = 2) AS clicks_count,
(SELECT Count(conversions.id)
FROM conversions
INNER JOIN clicks ON clicks.id = conversions.click_id
WHERE device_types.id = clicks.device_type_id
AND conversions.created_at BETWEEN "2021-07-06 00:00:00" AND "2021-07-08 23:59:59"
AND clicks.campaign_id = 2) AS conversions_count,
(SELECT sum(clicks.cost_integral)
FROM clicks
WHERE device_types.id = clicks.device_type_id
AND clicks.created_at BETWEEN "2021-07-06 00:00:00" AND "2021-07-08 23:59:59"
AND clicks.campaign_id = 2) AS cost_integral,
(SELECT sum(conversions.payout_integral)
FROM conversions
INNER JOIN clicks ON clicks.id = conversions.click_id
WHERE device_types.id = clicks.device_type_id
AND conversions.created_at BETWEEN "2021-07-06 00:00:00" AND "2021-07-08 23:59:59"
AND clicks.campaign_id = 2) AS revenue_integral
FROM device_types
INNER JOIN clicks ON clicks.device_type_id = device_types.id
WHERE clicks.campaign_id = 2
GROUP BY device_types.id) AS metrics
ORDER BY clicks_count DESC
Thank you for your help and time.
Edit:
One example is enough - the entire query does not need to be rebuilt. I only posted it because in the last thread someone told me to post the whole SQL command rather than just a fraction (I would have definitely shortened it otherwise).
It is important that these "Sub Selects" are not simple DB::raw("(SELECT COUNT(clicks.id) FROM .... Instead, I would like to know how to build these using the Laravel Query Builder.
That's how I would do that:
use Illuminate\Database\Query\Builder;
$clicksCount = DB::table('clicks')
->whereColumn('device_types.id', 'clicks.device_type_id')
->whereBetween('clicks.created_at', [ "2021-07-06 00:00:00", "2021-07-08 23:59:59" ])
->where('clicks.campaign_id', 2)
->select(DB::raw('Count(clicks.id)');
$conversionsCount = DB::table('conversions')
->join('clicks', 'clicks.id', 'conversions.click_id')
->whereColumn('device_types.id', 'clicks.device_type_id')
->whereBetween('conversions.created_at', [ "2021-07-06 00:00:00", "2021-07-08 23:59:59" ])
->where('clicks.campaign_id', 2)
->select(DB::raw('Count(conversions.id)'));
$costIntegral = DB::table('clicks')
->whereColumn('device_types.id', 'clicks.device_type_id')
->whereBetween('clicks.created_at', [ "2021-07-06 00:00:00", "2021-07-08 23:59:59" ])
->where('clicks.campaign_id', 2)
->select(DB::raw('sum(clicks.cost_integral)'));
$revenueIntegral = DB::table('conversions')
->join('clicks', 'clicks.id', 'conversions.click_id')
->whereColumn('device_types.id', 'clicks.device_type_id')
->whereBetween('conversions.created_at', [ "2021-07-06 00:00:00", "2021-07-08 23:59:59" ])
->where('clicks.campaign_id', 2)
->select(DB::raw('sum(clicks.payout_integral)'));
$metrics = DB::table('device_types')
->join('clicks', 'clicks.device_type_id', 'device_types.id')
->where('clicks.campaign_id', 2)
->groupBy('device_types.id')
->select('device_types.*')
->selectSub($clicksCount, 'clicks_count')
->selectSub($conversionsCount, 'conversions_count')
->selectSub($costIntegral, 'cost_integral')
->selectSub($revenueIntegral, 'revenue_integral');
Builder::newQuery()->select(
'id',
'name',
'clicks_count',
'conversions_count'
)
->selectRaw('
Round(((100 / clicks_count) * conversions_count), 2) AS conversion_rate,
Cast((cost_integral / clicks_count) AS UNSIGNED) AS cpc_integral,
Cast((Ifnull(revenue_integral, 0) / clicks_count) AS UNSIGNED) AS epc_integral,
Cast(Ifnull(revenue_integral, 0) AS signed) AS revenue_integral,
Cast(Ifnull(cost_integral, 0) AS UNSIGNED) AS cost_integral,
Cast((Ifnull(revenue_integral, 0) - cost_integral) AS signed) AS profit_integral,
Round((CASE
WHEN(Ifnull(revenue_integral, 0) = 0 AND Ifnull(cost_integral, 0) = 0) THEN 0
WHEN(Ifnull(revenue_integral, 0) = 0 AND Ifnull(cost_integral, 0) > 0) THEN -100
WHEN(Ifnull(revenue_integral, 0) > 0 AND Ifnull(cost_integral, 0) = 0) THEN 100
WHEN(Ifnull(revenue_integral, 0) > 0 AND Ifnull(cost_integral, 0) > 0) THEN ((revenue_integral / cost_integral) * 100)
END), 2) AS roi')
->fromSub($metrics, 'metrics')
->orderByDesc('clicks_count')
Please need some help to convert the below oracle code to Snowflake. When I m trying this, facing invalid identifier, rownum,
SELECT Customer_Id
,Release_type
,Customer_Name
,XYZ_Product_Name
,XYZ_Product_Salesforce_Number
,XYZ_Product_Code
,XYZ_Product_Type
,Brand_Family
,Qty_Purchased
,qty_u2dt
,sbc_Term_Start_Date
,sbc_Term_End_Date
,Months_Sold
,Months_Used
,Remaining_Months
,round(decode(Months_Sold, 0, 0, (Months_Used / Months_Sold) * 100), 2) AS Term_used_perc
,round(Actual_monthly_Usage, 2) AS Actual_monthly_Usage
,round((Actual_monthly_Usage * Remaining_Months) + qty_u2dt, 2) AS projected_usage
,round(decode(Qty_Purchased, 0, 0, (((Actual_monthly_Usage * Remaining_Months) + qty_u2dt) / Qty_Purchased) * 100), 2) AS projected_usage_perc
,round((((Actual_monthly_Usage * Remaining_Months) + qty_u2dt) - Qty_Purchased), 2) AS projected_over_under_usage
,CASE
WHEN round(decode(Qty_Purchased, 0, 0, (((Actual_monthly_Usage * Remaining_Months) + qty_u2dt) / Qty_Purchased) * 100), 2) = 100
AND Qty_Purchased = qty_u2dt
THEN 'Resell'
WHEN round(decode(Qty_Purchased, 0, 0, (((Actual_monthly_Usage * Remaining_Months) + qty_u2dt) / Qty_Purchased) * 100), 2) < 100
THEN 'Churn'
WHEN round(decode(Qty_Purchased, 0, 0, (((Actual_monthly_Usage * Remaining_Months) + qty_u2dt) / Qty_Purchased) * 100), 2) > 100
THEN 'Upsell'
WHEN round(decode(Qty_Purchased, 0, 0, (((Actual_monthly_Usage * Remaining_Months) + qty_u2dt) / Qty_Purchased) * 100), 2) = 100
AND Qty_Purchased = (round((Actual_monthly_Usage * Remaining_Months) + qty_u2dt))
THEN 'On Track'
ELSE 'Unknown'
END Projected_Indicator
,Timeline
,Contr_End_Date
,Salesforce_Account_Number
,Salesforce_csa_Id
,Salesforce_Contact
,Product_Family_Description
,Product_Family_Code
,Product_Brand_Description
,Product_Brand_Code
,Product_Category_Description
,Product_Category_Code
,Product_Name
,Product_Code
,product_type
,s_2_CUSTOMER_OWNER_NID
,G_Customer_Number
,G_Customer_Name
,G_Customer_Address
,G_Customer_City
,G_Customer_Country
,G_Customer_Phone
,G_Customer_State_Prov
,G_Customer_Zip_Code
,G_Customer_SFDC_NID
,G_Customer_SFDC_NID_Link
,s_2_Customer_Number
,s_2_Customer_Name
,s_2_Customer_Address
,s_2_Customer_City
,s_2_Customer_Country
,s_2_Customer_Phone
,s_2_Customer_State_Prov
,s_2_Customer_Zip_Code
,s_2_Customer_Health_Status
,s_2_Customer_SFDC_NID
,s_2_Customer_SFDC_NID_Link
,s_2_Customer_XYZ_NID
,s_2_Customer_XYZ_NID_Link
,s_2_Customer_Sales_Owner
,s_2_Customer_CSM
,s_2_Customer_CSM_Manager
,s_2_Customer_Sales_Manager
,s_2_customer_sales_team
,s_2_Customer_PSM
,s_2_Customer_PSM_Manager
,sbc_number
,sbc_status
,subscriptiontype
,sbc_start_date
,sbc_end_date
,sbc_termination_date
,sbc_SFDC_NID
,sbc_SFDC_NID_Link
,istestaccount
,child_sub_name
,parent_sub_name
,requiredbyid
,Parent_PRODUCTID
,parent_productname
,Initial_recurrinng_term
,Recurrinng_reolover_term
,renewal_date
,rate_set_uom
,Unit_of_Measure
,Contract_Number
,Contract_SFDC_NID
,Contract_SFDC_NID_Link
,Contract_Start_Date
,Contract_End_Date
FROM (
SELECT Customer_Id
,Release_type
,Customer_Name
--,Contract_Number
,XYZ_Product_Name
,XYZ_Product_Salesforce_Number
,XYZ_Product_Code
,XYZ_Product_Type
,Brand_Family
,Qty_Purchased
,qty_u2dt
,sbc_Term_Start_Date
,sbc_Term_End_Date
,round(months_between(sbc_Term_End_Date, sbc_Term_Start_Date), 2) AS Months_Sold
,round(months_between(current_date, sbc_Term_Start_Date), 2) AS Months_Used
,(round(months_between(sbc_Term_End_Date, sbc_Term_Start_Date), 2)) - (round(months_between(current_date, sbc_Term_Start_Date), 2)) AS Remaining_Months
,decode(months_between(current_date, sbc_Term_Start_Date), 0, 0, ((qty_u2dt / months_between(current_date, sbc_Term_Start_Date)))) AS Actual_monthly_Usage
,CASE
WHEN sbc_Term_End_Date < current_date
THEN 'Past'
WHEN sbc_Term_Start_Date > current_date
THEN 'Future'
ELSE 'Present'
END Timeline
,Contr_End_Date
,Salesforce_Account_Number
,Salesforce_csa_Id
,Salesforce_Contact
,Product_Family_Description
,Product_Family_Code
,Product_Brand_Description
,Product_Brand_Code
,Product_Category_Description
,Product_Category_Code
,Product_Name
,Product_Code
,product_type
,s_2_CUSTOMER_OWNER_NID
,G_Customer_Number
,G_Customer_Name
,G_Customer_Address
,G_Customer_City
,G_Customer_Country
,G_Customer_Phone
,G_Customer_State_Prov
,G_Customer_Zip_Code
,G_Customer_SFDC_NID
,G_Customer_SFDC_NID_Link
,s_2_Customer_Number
,s_2_Customer_Name
,s_2_Customer_Address
,s_2_Customer_City
,s_2_Customer_Country
,s_2_Customer_Phone
,s_2_Customer_State_Prov
,s_2_Customer_Zip_Code
,s_2_Customer_Health_Status
,s_2_Customer_SFDC_NID
,s_2_Customer_SFDC_NID_Link
,s_2_Customer_XYZ_NID
,s_2_Customer_XYZ_NID_Link
,s_2_Customer_Sales_Owner
,s_2_Customer_CSM
,s_2_Customer_CSM_Manager
,s_2_Customer_Sales_Manager
,s_2_customer_sales_team
,s_2_Customer_PSM
,s_2_Customer_PSM_Manager
,sbc_number
,sbc_status
,subscriptiontype
,sbc_start_date
,sbc_end_date
,sbc_termination_date
,sbc_SFDC_NID
,sbc_SFDC_NID_Link
,istestaccount
,child_sub_name
,parent_sub_name
,requiredbyid
,Parent_PRODUCTID
,parent_productname
,Initial_recurrinng_term
,Recurrinng_reolover_term
,renewal_date
,rate_set_uom
,Unit_of_Measure
,Contract_Number
,Contract_SFDC_NID
,Contract_SFDC_NID_Link
,Contract_Start_Date
,Contract_End_Date
FROM (
SELECT DISTINCT cust.Id AS Customer_Id
,sub.rtpname AS Release_type
,org.Name AS Customer_Name
,prod.Name AS XYZ_Product_Name
,prod.SalesforceId AS XYZ_Product_Salesforce_Number
,prod.Code AS XYZ_Product_Code
,prod.Type AS XYZ_Product_Type
,pb.Name AS Brand_Family
,cntr.CURRENCYISOCODE AS currency_code
,nvl((
SELECT *
FROM (
SELECT to_char(cliterm.Quantity)
FROM XYZ_ContractLineItemTerm cliterm
WHERE cliterm.ContractLineItem_id = cli.Id
AND (
cliterm.EndDate IS NULL
OR cliterm.EndDate > add_months(current_date, - 3)
)
AND cliterm.PriceRuleItem_id IS NULL
ORDER BY cli.id DESC
)
WHERE rownum = 1
), cli.Quantity) AS Qty_Purchased
,nvl((
SELECT *
FROM (
SELECT cliterm.UsedQuantity
FROM XYZ_ContractLineItemTerm cliterm
WHERE cliterm.ContractLineItem_id = cli.Id
AND (
cliterm.EndDate IS NULL
OR cliterm.EndDate > add_months(current_date, - 3)
)
AND cliterm.PriceRuleItem_id IS NULL
ORDER BY cli.id DESC
)
WHERE rownum = 1
), cli.UsedQuantity) AS qty_u2dt
,nvl((
SELECT *
FROM (
SELECT cliterm.StartDate
FROM XYZ_ContractLineItemTerm cliterm
WHERE cliterm.ContractLineItem_id = cli.Id
AND (
cliterm.EndDate IS NULL
OR cliterm.EndDate > add_months(current_date, - 3)
)
AND cliterm.PriceRuleItem_id IS NULL
ORDER BY cli.id DESC
)
WHERE rownum = 1
), cli.StartDate) AS sbc_Term_Start_Date
,nvl((
SELECT *
FROM (
SELECT cliterm.EndDate
FROM XYZ_ContractLineItemTerm cliterm
WHERE cliterm.ContractLineItem_id = cli.Id
AND (
cliterm.EndDate IS NULL
OR cliterm.EndDate > add_months(current_date, - 3)
)
AND cliterm.PriceRuleItem_id IS NULL
ORDER BY id DESC
)
WHERE rownum = 1
), cli.EndDate) AS sbc_Term_End_Date
,nvl(to_char(cli.EndDate), (
CASE
WHEN (
cli.StartDate IS NOT NULL
AND con.InitialTerm > 0
)
THEN 'Auto Renewal'
ELSE ''
END
)) AS Contr_End_Date
,cust.SalesforceAccountNumber AS Salesforce_Account_Number
,cust.SalesforceId AS Salesforce_csa_Id
,'s12345' || con.SalesforceId || '/view' AS Salesforce_Contact
,prod_fam.product_family_code AS product_family_code
,prd.Product_Family__c AS Product_Family_Description
,prd.Brand_Code__c AS Product_Brand_Code
,prd.Product_Brand__c AS Product_Brand_Description
,prd.Category_Code__c AS Product_Category_Code
,prd.Product_Category__c AS Product_Category_Description
,prd.name AS Product_Name
,prd.productcode AS Product_Code
,prd.PRODUCT_TYPE__C AS product_type
,dasruler.id AS s_2_CUSTOMER_OWNER_NID
,rupa.global_ultimate_d_u_n_s_number AS G_Customer_Number
,rupa.name AS G_Customer_Name
,rupa.billingstreet AS G_Customer_Address
,rupa.billingcity AS G_Customer_City
,rupa.billingcountry AS G_Customer_Country
,rupa.phone AS G_Customer_Phone
,rupa.billingstate AS G_Customer_State_Prov
,rupa.billingpostalcode AS G_Customer_Zip_Code
,rupa.id AS G_Customer_SFDC_NID
,'12345'|| rupa.id || '/view' AS G_Customer_SFDC_NID_Link
,csa.csa__c AS s_2_Customer_Number
,csa.name AS s_2_Customer_Name
,csa.account_address__c AS s_2_Customer_Address
,csa.account_city__c AS s_2_Customer_City
,csa.account_country__c AS s_2_Customer_Country
,csa.phone AS s_2_Customer_Phone
,csa.account_state_province__c AS s_2_Customer_State_Prov
,csa.account_zip_code__c AS s_2_Customer_Zip_Code
,csa.id AS s_2_Customer_SFDC_NID
,'12345' || csa.id || '/view' AS s_2_Customer_SFDC_NID_Link
,csa.client_health_status__c s_2_Customer_Health_Status
,cust.id AS s_2_Customer_XYZ_NID
,'q12345' || cust.id || '/view' AS s_2_Customer_XYZ_NID_Link
,nvl(dasruler.firstname || ' ' || dasruler.lastname, 'UNKNOWN') AS s_2_Customer_Sales_Owner
,nvl(csacsm.csm, 'UNKNOWN') AS s_2_Customer_CSM
,nvl(csm_mgr.NAME, 'NAVL') AS s_2_Customer_CSM_Manager
,nvl(csasalesmanager.firstname || ' ' || csasalesmanager.lastname, 'UNKNOWN') AS s_2_Customer_Sales_Manager
,nvl(csasalesmanager.USER_SEGMENT__C, 'UNKNOWN') AS s_2_customer_sales_team
,nvl(csapsm.psm, 'NAVL') AS s_2_Customer_PSM
,nvl(psm_mgr.name, 'NAVL') AS s_2_Customer_PSM_Manager
,sub.name AS sbc_number
,sub.STATUS__C AS sbc_status
,sub.sbqq__subscriptiontype__c AS subscriptiontype
,nvl(sub.sbqq__subscriptionstartdate__c, sub.sbqq__startdate__c) AS sbc_start_date
,sub.SBQQ__ENDDATE__C AS sbc_end_date
,sub.sbqq__terminateddate__c AS sbc_termination_date
,sub.annual_recurring_total__c AS annual_recurring_total__c
,sub.one_time_total__c AS one_time_total__c
,sub.currencyisocode AS Localcurrency
,sub.id AS sbc_SFDC_NID
,'z12345' || sub.id || '/view' AS sbc_SFDC_NID_Link
,sub.name AS child_sub_name
,sub.RECURRING_INITIAL_TERM__C AS Initial_recurrinng_term
,sub.RECURRING_ROLLOVER_TERM__C AS Recurrinng_reolover_term
,sub.RENEWAL_DATE__C AS renewal_date
,pasub.name AS parent_sub_name
,sub.sbqq__requiredbyid__c AS requiredbyid
,pasub.SBQQ__PRODUCTID__C AS Parent_PRODUCTID
,pasub.SBQQ__PRODUCTNAME__C AS Parent_Productname
,csa.is_test_account__c AS istestaccount
,prd.rate_set_uom__C AS rate_set_uom
,PRD.Quantity_unit_of_measure__C AS Unit_of_Measure
,cntr.CONTRACTNUMBER AS Contract_Number
,cntr.id AS Contract_SFDC_NID
,'c123456'|| cntr.id || '/view' AS Contract_SFDC_NID_Link
,cntr.startdate AS Contract_Start_Date
,cntr.enddate AS Contract_End_Date
,cntr.annual_recurring_total__c AS Contract_annual_recurring_amt
,cntr.one_time_total__c AS Contract_one_time_total
,cntr.initial_term_total__c AS First_year_contract_value
FROM XYZ_ContractLineItem cli
INNER JOIN XYZ_Contract con ON cli.Contract_id = con.Id
INNER JOIN XYZ_Customer cust ON con.Customer_id = cust.Id
INNER JOIN XYZ_Organization org ON org.Customer_id = cust.Id
INNER JOIN XYZ_Product prod ON cli.Product_id = prod.Id
INNER JOIN XYZ_ProductBrand pb ON prod.ProductBrand_id = pb.Id
LEFT JOIN sfacc csa ON cust.SalesforceAccountNumber = csa.csa__c
LEFT JOIN sfacc rupa ON csa.parentid = rupa.id
LEFT JOIN sf_SBQQ__sbc__C sub ON sub.id = cli.salesforceid
LEFT JOIN SF_SBQQ__sbc__C pasub ON pasub.id = sub.sbqq__requiredbyid__c
LEFT JOIN contractor cntr ON cntr.contractnumber = con.ContractNumber
LEFT JOIN sfu dasruler ON csa.ownerid = dasruler.id
LEFT JOIN sfu dassalesmgr ON dasruler.managerid = dassalesmgr.id
LEFT JOIN (
SELECT f.accountid
,g.managerid
,max(g.NAME) CSM
,max(g.id) CSMID
FROM sfatm f
JOIN sfu g ON f.userid = g.id
WHERE f.teammemberrole = 'AGM'
GROUP BY f.accountid
,g.managerid
) dasagm ON dasagm.accountid = csa.id
LEFT JOIN sfu csm_mgr ON dasagm.managerid = csm_mgr.id
LEFT JOIN (
SELECT f.accountid
,g.managerid
,max(g.NAME) PSM
,max(g.id) CSMID
FROM sfatm f
JOIN sfu g ON f.userid = g.id
WHERE f.teammemberrole = 'SDM'
GROUP BY f.accountid
,g.managerid
) dassdm ON dassdm.accountid = csa.id
LEFT JOIN sfu psm_mgr ON dassdm.managerid = psm_mgr.id
LEFT JOIN SFP prd ON prod.Code = prd.productcode
LEFT JOIN IPFam prod_fam ON prod_fam.product_family_desc = prd.Product_Family__c
WHERE cli.RateEffectiveStatus = 'A'
AND cli.STATUS = 'A'
AND cli.Active = 1
AND con.STATUS IN ('A')
AND CUST.STATUS = 'active'
AND prod.type <> 'KING'
AND csa.itac = 0
)
WHERE Qty_Purchased <> 0
);
Snowflake doesn't have a ROWNUM keyword as Oracle does.
If you want to use that functionality, you can generate an equivalent using the window function, row_number(). This would typically be done by inserting that window function into the bottom level of your query.
I have such a problem and I don't know how to solve it, can you help me? t
The query returns a result that is shown on the photo and I want to get it to be shown in one line instead of many based on type of age.
https://imgur.com/a/OA6CBpa
with x as (
select ai.invoice_id, ai.invoice_num, ai.invoice_amount, ai.amount_paid,
trial.entity_id, trial.acctd_amount, trial.entered_amount, trial.gl_date,
aps.amount_remaining, aps.gross_amount, aps.due_date, aps.payment_status_flag,
trial.gl_date - aps.due_date dni_opoznienia
from ap_invoices_all ai,
xla.xla_transaction_entities xte,
(
select nvl (tr.applied_to_entity_id, tr.source_entity_id) entity_id,
tr.source_application_id application_id,
sum (nvl (tr.acctd_unrounded_cr, 0)) - sum (nvl (tr.acctd_unrounded_dr, 0)) acctd_amount,
sum (nvl (tr.entered_unrounded_cr, 0)) - sum (nvl (tr.entered_unrounded_dr, 0)) entered_amount,
max(tr.gl_date) gl_date
from xla.xla_trial_balances tr
where 1=1
and tr.definition_code = 'AP_200_1001'
and tr.source_application_id = 200
and tr.gl_date <= fnd_date.canonical_to_date('2019-12-13') -- Data KG
group by nvl (tr.applied_to_entity_id, tr.source_entity_id),
tr.source_application_id
) trial,
ap_payment_schedules_all aps
where 1=1
and ai.invoice_id = 3568325
and nvl(xte.source_id_int_1, -99) = ai.invoice_id
and xte.ledger_id = 1001
and xte.entity_code = 'AP_INVOICES'
and xte.entity_id = trial.entity_id
and xte.application_id = trial.application_id
and ai.invoice_id = aps.invoice_id
)
select x.invoice_id, x.invoice_num, x.entity_id, x.acctd_amount, x.gl_date,
x.amount_remaining, x.gross_amount, x.due_date, x.payment_status_flag,
x.dni_opoznienia, aapl.days_start, aapl.days_to,
case
when x.dni_opoznienia between aapl.days_start and aapl.days_to then x.acctd_amount
else 0
end przedzial
from x,
ap_aging_periods aap,
ap_aging_period_lines aapl
where 1=1
and aap.period_name = 'TEST 5 okresow'
and aap.aging_period_id = aapl.aging_period_id
Based on your comment I guess you need the below
select * from (select x.invoice_id, x.invoice_num, x.entity_id, x.acctd_amount, x.gl_date,
x.amount_remaining, x.gross_amount, x.due_date, x.payment_status_flag,
x.dni_opoznienia, aapl.days_start, aapl.days_to,
case
when x.dni_opoznienia between aapl.days_start and aapl.days_to then x.acctd_amount
else 0
end przedzial
from x,
ap_aging_periods aap,
ap_aging_period_lines aapl
where 1=1
and aap.period_name = 'TEST 5 okresow'
and aap.aging_period_id = aapl.aging_period_id)
where przedzial > 0;
I have tried following query, which is returning all lines for each STOCKCODE, where as I am only after record with earliest PurchOrd_Lines.Due Date
SELECT
PURCHORD_LINES.STOCKCODE,
STOCK_ITEMS.DESCRIPTION,
(X_FREE_STOCK_VW.PhysicalQty - X_FREE_STOCK_VW.CommittedQty) AS 'FREE STOCK',
X_FREE_STOCK_VW.PhysicalQty AS 'On Hand',
X_FREE_STOCK_VW.CommittedQty AS 'Committed',
X_FREE_STOCK_VW.IncommingQty AS 'Purch_Ord',
PURCHORD_LINES.HDR_SEQNO,
(PURCHORD_LINES.ORD_QUANT-PURCHORD_LINES.SUP_QUANT) AS 'QTY',
CONVERT(DATETIME, MIN(PURCHORD_LINES.DUEDATE), 103) AS 'ETA',
PURCHORD_HDR.X_PURCHASEORDERREF AS 'Reference'
FROM
PURCHORD_LINES PURCHORD_LINES
JOIN
STOCK_ITEMS ON STOCK_ITEMS.STOCKCODE = PURCHORD_LINES.STOCKCODE
JOIN
X_FREE_STOCK_VW ON X_FREE_STOCK_VW.STOCKCODE = PURCHORD_LINES.STOCKCODE
JOIN
PURCHORD_HDR ON PURCHORD_HDR.SEQNO = PURCHORD_LINES.HDR_SEQNO
WHERE
X_FREE_STOCK_VW.LOCATION = 1
AND STOCK_ITEMS.STOCK_CLASSIFICATION IN (0,10,20,200,210,220)
AND STOCK_ITEMS.STOCKCODE NOT LIKE '%2' AND STOCK_ITEMS.STOCKCODE NOT LIKE '%3'
AND (X_FREE_STOCK_VW.PhysicalQty - X_FREE_STOCK_VW.CommittedQty) <= 0
AND X_FREE_STOCK_VW.CommittedQty > 0
AND LEN(STOCK_ITEMS.STOCKCODE) > 6
AND STOCK_ITEMS.DESCRIPTION IS NOT NULL
AND STOCK_ITEMS.DESCRIPTION != ''
AND STOCK_ITEMS.SUPPLIERNO IN (1009, 1024, 1068, 1115, 1146, 1170, 1259, 1306, 1410, 2768)
AND STOCK_ITEMS.X_BUYER = 'P'
AND ((PURCHORD_LINES.ORD_QUANT - PURCHORD_LINES.SUP_QUANT) > 0 AND
(PURCHORD_LINES.SUP_QUANT/PURCHORD_LINES.ORD_QUANT) < 0.9)
AND ((PURCHORD_HDR.STATUS <> 2)
AND (PURCHORD_HDR.X_DELIVERYSTATUS <> 4)
AND (PURCHORD_LINES.ORD_QUANT > 0))
GROUP BY
PURCHORD_LINES.STOCKCODE, STOCK_ITEMS.DESCRIPTION,
X_FREE_STOCK_VW.PhysicalQty, X_FREE_STOCK_VW.CommittedQty,
X_FREE_STOCK_VW.IncommingQty, PURCHORD_LINES.HDR_SEQNO,
PURCHORD_LINES.ORD_QUANT, PURCHORD_LINES.SUP_QUANT,
PURCHORD_HDR.X_PURCHASEORDERREF
Output is
STOCKCODE| FREE STOCK |On Hand |Committed|Purch_Ord|HDR_SEQNO|QTY|ETA |Reference
42165 | -351 |-29 |322 |406 |106200 |84 |21/02/2020 |426/19
42165 | -351 |-29 |322 |406 |107052 |87 |20/03/2020 |454/19
42165 | -351 |-29 |322 |406 |107626 |150|11/04/2020 |024/20
42166 | -15 |41 |57 |406 |107626 |150|13/02/2020 |074/20
42166 | -15 |41 |57 |406 |107626 |150|17/02/2020 |089/20
WHEREAS I only need it to return the row with earliest date(ETA) for each stock code. What am doing wrong?
You can make use of row_number to achieve this
with data
as ( /*The original query*/
SELECT
PURCHORD_LINES.STOCKCODE,
STOCK_ITEMS.DESCRIPTION,
(X_FREE_STOCK_VW.PhysicalQty - X_FREE_STOCK_VW.CommittedQty) AS 'FREE STOCK',
X_FREE_STOCK_VW.PhysicalQty AS 'On Hand',
X_FREE_STOCK_VW.CommittedQty AS 'Committed',
X_FREE_STOCK_VW.IncommingQty AS 'Purch_Ord',
PURCHORD_LINES.HDR_SEQNO,
(PURCHORD_LINES.ORD_QUANT-PURCHORD_LINES.SUP_QUANT) AS 'QTY',
CONVERT(DATETIME, MIN(PURCHORD_LINES.DUEDATE), 103) AS 'ETA',
PURCHORD_HDR.X_PURCHASEORDERREF AS 'Reference'
FROM PURCHORD_LINES PURCHORD_LINES
JOIN STOCK_ITEMS ON STOCK_ITEMS.STOCKCODE = PURCHORD_LINES.STOCKCODE
JOIN X_FREE_STOCK_VW ON X_FREE_STOCK_VW.STOCKCODE = PURCHORD_LINES.STOCKCODE
JOIN PURCHORD_HDR ON PURCHORD_HDR.SEQNO = PURCHORD_LINES.HDR_SEQNO
WHERE X_FREE_STOCK_VW.LOCATION = 1
AND STOCK_ITEMS.STOCK_CLASSIFICATION IN (0,10,20,200,210,220)
AND STOCK_ITEMS.STOCKCODE NOT LIKE '%2' AND STOCK_ITEMS.STOCKCODE NOT LIKE '%3'
AND (X_FREE_STOCK_VW.PhysicalQty - X_FREE_STOCK_VW.CommittedQty) <= 0
AND X_FREE_STOCK_VW.CommittedQty > 0
AND LEN(STOCK_ITEMS.STOCKCODE) > 6
AND STOCK_ITEMS.DESCRIPTION IS NOT NULL
AND STOCK_ITEMS.DESCRIPTION != ''
AND STOCK_ITEMS.SUPPLIERNO IN (1009,1024,1068,1115,1146,1170,1259,1306,1410,2768)
AND STOCK_ITEMS.X_BUYER = 'P'
AND ((PURCHORD_LINES.ORD_QUANT - PURCHORD_LINES.SUP_QUANT) > 0 AND (PURCHORD_LINES.SUP_QUANT/PURCHORD_LINES.ORD_QUANT)<0.9)
AND ((PURCHORD_HDR.STATUS<>2)
AND (PURCHORD_HDR.X_DELIVERYSTATUS<>4)
AND (PURCHORD_LINES.ORD_QUANT>0))
GROUP BY PURCHORD_LINES.STOCKCODE
, STOCK_ITEMS.DESCRIPTION
, X_FREE_STOCK_VW.PhysicalQty
, X_FREE_STOCK_VW.CommittedQty
, X_FREE_STOCK_VW.IncommingQty
, PURCHORD_LINES.HDR_SEQNO
, PURCHORD_LINES.ORD_QUANT
, PURCHORD_LINES.SUP_QUANT
, PURCHORD_HDR.X_PURCHASEORDERREF
)
,interim_data
as (
select *,row_number() over(partition by stockcode order by eta asc) as rnk
from data
)
select *
from iterim_data
where rnk=1
Maybe this way can help:
SELECT ETA, *
FROM (SELECT PURCHORD_LINES.STOCKCODE,
CONVERT(DATETIME, MIN(PURCHORD_LINES.DUEDATE), 103) AS 'ETA'
FROM PURCHORD_LINES PURCHORD_LINES
GROUP BY PURCHORD_LINES.STOCKCODE ) as PURCHORD_ETA
JOIN PURCHORD_LINES ON PURCHORD_LINES.STOCKCODE = PURCHORD_ETA.STOCKCODE
JOIN ...
WHERE ...
GROUP BY ...
Try Subqueries, it will be easier to understand