Trying to add a syntax in existing query (Custom SQL) - sql

I am trying to add a condition to existing SQL Query but I am no expert at SQL & requesting some help here.
I have the below SQL query & I currently have PARNT_SLS_ORDER_LINE_KEY that I am pulling for two BUSINESS_UNIT_ID ('CSPBU', 'TMGBU'). In the existing query I am trying to add a condition like:
If PARNT_SLS_ORDER_LINE_KEY exists in both CSPBU & TMGBU then output or ignore.
SELECT
BV_PRODUCTS.PRODUCT_ID,
BV_FISCAL_DAY_TO_YEAR.FISCAL_YEAR_NUMBER_INT,
BV_FISCAL_DAY_TO_YEAR.FISCAL_QUARTER_ID,
SUM(CASE WHEN DT_MT_RSTD_BKGS_MEASURE_IE_BE.SERVICE_FLG = 'N' THEN DT_MT_RSTD_BKGS_MEASURE_IE_BE.EXTENDED_QUANTITY*COALESCE(BV_BE_HIER_PRDT_FAM_ALLOC_INT.PRDT_FAMILY_ALLOCATION_PCT,1)*COALESCE(BV_BE_HIER_PRDT_FMLY_ALLOC_EXT.PRDT_FAMILY_ALLOCATION_PCT,1) ELSE 0 END) Quanity
,
sum(CASE WHEN DT_MT_RSTD_BKGS_MEASURE_IE_BE.SERVICE_FLG = 'N' THEN DT_MT_RSTD_BKGS_MEASURE_IE_BE.COMP_US_NET_PRICE_AMOUNT*COALESCE(BV_BE_HIER_PRDT_FAM_ALLOC_INT.PRDT_FAMILY_ALLOCATION_PCT,1)*COALESCE(BV_BE_HIER_PRDT_FMLY_ALLOC_EXT.PRDT_FAMILY_ALLOCATION_PCT,1) ELSE 0 END) Net_Price,
BV_SALES_ORDER_LINE.PARNT_SLS_ORDER_LINE_KEY,
BV_PRODUCTS.BUSINESS_UNIT_ID
FROM
FINANCEBOBVDB.BV_PRODUCTS,
FINANCEBOBVDB.BV_FISCAL_DAY_TO_YEAR,
FINANCEBOBVDB.BV_BE_HIER_PRDT_FAMILY_ALLOC BV_BE_HIER_PRDT_FAM_ALLOC_INT,
FINANCEBOBVDB.BV_BE_HIER_PRDT_FMLY_ALLOC_EXT,
(
SELECT BV_MT_RSTD_BKGS_MEASURE.* , BV_FISCAL_DAY_TO_YEAR.FISCAL_YEAR_QUARTER_NUMBER_INT ,
BV_FISCAL_DAY_TO_YEAR.CALENDAR_DATE
FROM FINANCEBOBVDB.BV_MT_RSTD_BKGS_MEASURE , FINANCEBOBVDB.BV_FISCAL_DAY_TO_YEAR
WHERE BV_MT_RSTD_BKGS_MEASURE.BOOKINGS_PROCESS_DATE = BV_FISCAL_DAY_TO_YEAR.CALENDAR_DATE
AND BV_FISCAL_DAY_TO_YEAR.FISCAL_YEAR_MONTH_INT >= 201001
) DT_MT_RSTD_BKGS_MEASURE_IE_BE,
BV_SALES_ORDER_LINE
WHERE
( BV_BE_HIER_PRDT_FAM_ALLOC_INT.ITEM_KEY=DT_MT_RSTD_BKGS_MEASURE_IE_BE.PRODUCT_KEY AND BV_BE_HIER_PRDT_FAM_ALLOC_INT.FISCAL_YEAR_QUARTER_NUMBER_INT=DT_MT_RSTD_BKGS_MEASURE_IE_BE.FISCAL_YEAR_QUARTER_NUMBER_INT )
AND ( BV_BE_HIER_PRDT_FMLY_ALLOC_EXT.ITEM_KEY=DT_MT_RSTD_BKGS_MEASURE_IE_BE.PRODUCT_KEY AND BV_BE_HIER_PRDT_FMLY_ALLOC_EXT.FISCAL_YEAR_QUARTER_NUMBER_INT=DT_MT_RSTD_BKGS_MEASURE_IE_BE.FISCAL_YEAR_QUARTER_NUMBER_INT )
AND ( DT_MT_RSTD_BKGS_MEASURE_IE_BE.BOOKINGS_PROCESS_DATE=BV_FISCAL_DAY_TO_YEAR.CALENDAR_DATE )
AND ( BV_PRODUCTS.ITEM_KEY=DT_MT_RSTD_BKGS_MEASURE_IE_BE.PRODUCT_KEY )
AND ( BV_SALES_ORDER_LINE.SALES_ORDER_LINE_KEY=DT_MT_RSTD_BKGS_MEASURE_IE_BE.DV_SALES_ORDER_LINE_KEY )
AND ( DT_MT_RSTD_BKGS_MEASURE_IE_BE.PRODUCT_KEY IN ( SELECT ITEM_KEY FROM FINANCEBOBVDB.BV_PRODUCTS H JOIN FINANCEBOBVDB.BV_IAM_TECHNOLOGY_GROUP_LINK S ON H.TECHNOLOGY_GROUP_ID = S.TECHNOLOGY_GROUP_ID WHERE cec_id='meramesh' AND IAM_LEVEL_NUM=1 ) )
AND ( DT_MT_RSTD_BKGS_MEASURE_IE_BE.DV_ATTRIBUTION_CD IN ('ATTRIBUTED','STANDALONE') )
AND
(
DT_MT_RSTD_BKGS_MEASURE_IE_BE.REVENUE_RECOGNITION_FLG IN ( 'Y' )
AND
BV_FISCAL_DAY_TO_YEAR.FISCAL_YEAR_NUMBER_INT IN ( 2018, 2019, 2020 )
AND
BV_PRODUCTS.BUSINESS_UNIT_ID IN ( 'cspbu', 'tmgbu' )
)
GROUP BY
1,
2,
3,
6,
7

How are you grouping your rows -- by product_id? If you want to only return rows where a given product_id has PARNT_SLS_ORDER_LINE_KEY with both values of TMGBU and CSPBU, then you can add this to the end of your query:
QUALIFY
MAX(CASE PARNT_SLS_ORDER_LINE_KEY WHEN 'CSPBU' THEN 1 WHEN 'TMGBU' THEN 2 END)
OVER(PARTITION BY BV_PRODUCTS.PRODUCT_ID) <>
MIN(CASE PARNT_SLS_ORDER_LINE_KEY WHEN 'CSPBU' THEN 1 WHEN 'TMGBU' THEN 2 END)
OVER(PARTITION BY BV_PRODUCTS.PRODUCT_ID)
Give it a try and let me know.

Related

check for a column if it is null , over a previous term with some conditions

I have lets say two terms term A (previous)and term B (current) , i need to check if pol_cancl_date is null or not in term A , there is a transaction_sequence_number , i need to see if the pol_cncl_date is existing in the greatest A.transaction_sequence_number and if greatest( A.transaction_sequence_number ) is the greated when compared to all B.transaction_sequence_number numbers , if it is then i would want to check for pol_cancl_dates's existence and apply a logic
WITH x AS (
SELECT * FROM (
SELECT
pol_num
,term_start_dt
,term_end_dt,pol_cancel_dt
,trans_seq_num
,future_cancel_dt
,DENSE_RANK() OVER (PARTITION BY pol_num ORDER BY term_end_dt DESC) AS flag
FROM `gcp-ent-datalake-preprod.trns_prop_pol_hs_horison.prop_cost`
--WHERE pol_num IN ('30766675','33896642')
-- pol_num = '33288489'
ORDER BY term_start_dt, term_end_dt DESC
)
)
SELECT
*
,CASE
WHEN prior_pol_cancel_dt IS NOT NULL AND current_trans_seq_num < prior_trans_seq_num THEN prior_pol_cancel_dt
ELSE current_pol_cancel_dt
END apply_cancelled_renewal_dt
FROM (
SELECT
MAX(a.pol_num) AS current_pol_num
,MAX(a.term_start_dt) AS current_term_start_dt
,a.term_end_dt AS current_term_ent_dt
,MAX(a.pol_cancel_dt) AS current_pol_cancel_dt
,MAX(a.trans_seq_num) AS current_trans_seq_num
,MAX(a.future_cancel_dt) AS current_future_cancel_dt
,MAX(a.flag) AS current_flag
,MAX(b.pol_num) AS prior_pol_num
,MAX(b.term_start_dt) AS prior_term_start_dt
,b.term_end_dt AS prior_term_end_dt
,MAX(b.pol_cancel_dt) AS prior_pol_cancel_dt
,MAX(b.trans_seq_num) AS prior_trans_seq_num
,MAX(b.future_cancel_dt) AS prior_future_cancel_dt
,MAX(b.flag) AS prior_flag
FROM (
SELECT * FROM x WHERE flag=1) a
INNER JOIN(
SELECT * FROM x WHERE flag = 2 ) b
ON a.pol_num = b.pol_num AND a.flag = b.flag - 1
WHERE a.pol_cancel_dt IS NOT NULL
AND b.pol_cancel_dt IS NOT NULL
AND greatest(a.trans_seq_num) < b.trans_seq_num
-- AND a.trans_seq_num = GREATEST(a.trans_seq_num)
-- AND b.trans_seq_num = GREATEST(b.trans_seq_num)
GROUP BY a.term_end_dt, b.term_end_dt
)
--WHERE a.term_start_dt < b.term_start_dt
--if prior term GREATEST (trans_sewq num
this logic is still not giving me some results , one thing is that trans_seq_num doesn't necessarily have to be one less

how to use case with group by?

the query works well but when iam adding group by it gives me [Error] ORA-01427 here is the main query
SELECT DISTINCT Contract_number,
area_number,
area_name,
ADVANCE_PAY,
Postponed_Amount,
extract_number,
total
FROM (SELECT xxr.Contract_num Contract_number,
xxr.p_area_no area_number,
xxr.p_area_name area_name,
xxr.ADVANCE_PAY ADVANCE_PAY,
xxr.DEFERRED_BOOST Postponed_Amount,
xxr.release_num extract_number,
and here is the case statement :
(SELECT DISTINCT
CASE
WHEN :p_item_code IS NOT NULL
THEN
TOTAL_AMOUNT
WHEN :p_item_code IS NULL
THEN
( (SELECT NVL (SUM (TOTAL_AMOUNT), 0)
FROM XXEXTRACT.XXNATGAS_REALSES_LINES
WHERE XXEXTRACT.XXNATGAS_REALSES.release_id =
XXEXTRACT.XXNATGAS_REALSES_LINES.release_id))
ELSE
NULL
END
FROM XXEXTRACT.XXNATGAS_REALSES_LINES xxrl,
XXEXTRACT.XXNATGAS_REALSES
WHERE 1 = 1
AND xxrl.release_id =
XXEXTRACT.XXNATGAS_REALSES.release_id)
AS total
and here is the from part :
FROM XXEXTRACT.XXNATGAS_REALSES_LINES xxrl,
XXEXTRACT.XXNATGAS_REALSES xxr
WHERE 1 = 1
AND xxrl.release_id = xxr.release_id
AND xxr.release_date >= NVL (:p_date_from, xxr.release_date)
AND xxr.release_date <= NVL (:p_date_to, xxr.release_date)
AND xxr.Contract_num = NVL (:p_cont_num, xxr.Contract_num)
AND xxr.vendor_id = NVL (:p_ven_id, xxr.vendor_id)
AND xxr.vendor_site_id = NVL (:p_site_id, xxr.vendor_site_id)
)
and here is the group by :
GROUP BY Contract_number,
area_number,
area_name,
ADVANCE_PAY,
Postponed_Amount,
extract_number,
total;
these is the full query so please any help
For sure I couldn't understand very well your query. You could improve your post for next time.
As answer, I think you should encapsulate your select statment and group by using your select as subquery. It is not the best approach but it may works fine.
select *
from (
select distinct Contract_number
,area_number
,area_name
,ADVANCE_PAY
,Postponed_Amount
,extract_number
,total
from (
select xxr.Contract_num Contract_number
,xxr.p_area_no area_number
,xxr.p_area_name area_name
,xxr.ADVANCE_PAY ADVANCE_PAY
,xxr.DEFERRED_BOOST Postponed_Amount
,xxr.release_num extract_number
,(
select distinct case
when :p_item_code is not null
then TOTAL_AMOUNT
when :p_item_code is null
then (
(
select NVL(SUM(TOTAL_AMOUNT), 0)
from XXEXTRACT.XXNATGAS_REALSES_LINES
where XXEXTRACT.XXNATGAS_REALSES.release_id = XXEXTRACT.XXNATGAS_REALSES_LINES.release_id
)
)
else null
end
from XXEXTRACT.XXNATGAS_REALSES_LINES xxrl
,XXEXTRACT.XXNATGAS_REALSES
where 1 = 1
and xxrl.release_id = XXEXTRACT.XXNATGAS_REALSES.release_id
) as total
from XXEXTRACT.XXNATGAS_REALSES_LINES xxrl
,XXEXTRACT.XXNATGAS_REALSES xxr
where 1 = 1
and xxrl.release_id = xxr.release_id
and xxr.release_date >= NVL(:p_date_from, xxr.release_date)
and xxr.release_date <= NVL(:p_date_to, xxr.release_date)
and xxr.Contract_num = NVL(:p_cont_num, xxr.Contract_num)
and xxr.vendor_id = NVL(:p_ven_id, xxr.vendor_id)
and xxr.vendor_site_id = NVL(:p_site_id, xxr.vendor_site_id)
)
) TBL1
group by TBL1.Contract_number
,TBL1.area_number
,TBL1.area_name
,TBL1.ADVANCE_PAY
,TBL1.Postponed_Amount
,TBL1.extract_number
,TBL1.total;

How to add a count/sum and group by in a CTE

Just a question on displaying a row on flight level and displaying a count on how many crew members on that flight.
I want to change the output so it will only display a single record at flight level and it will display two additional columns. One column (cabincrew) is the count of crew members that have the 'CREWTYPE' = 'F' and the other column (cockpitcrew) is the count of crew members that have the `'CREWTYPE' = 'C'.
So the query result should look like:
Flight DepartureDate DepartureAirport CREWBASE CockpitCrew CabinCrew
LS361 2016-05-19 BFS BFS 0 3
Can I have a little help tweaking the below query please:
WITH CTE AS (
SELECT cd.*, c.*, l.Carrier, l.FlightNumber, l.Suffix, l.ScheduledDepartureDate, l.ScheduledDepartureAirport
FROM
(SELECT *, ROW_NUMBER() OVER(PARTITION BY LegKey ORDER BY UpdateID DESC) AS RowNumber FROM Data.Crew) c
INNER JOIN
Data.CrewDetail cd
ON c.UpdateID = cd.CrewUpdateID
AND cd.IsPassive = 0
AND RowNumber = 1
INNER JOIN
Data.Leg l
ON c.LegKey = l.LegKey
)
SELECT
sac.Airline + CAST(sac.FlightNumber AS VARCHAR) + sac.Suffix AS Flight
, sac.DepartureDate
, sac.DepartureAirport
, sac.CREWBASE
, sac.CREWTYPE
, sac.EMPNO
, sac.FIRSTNAME
, sac.LASTNAME
, sac.SEX
FROM
Staging.SabreAssignedCrew sac
LEFT JOIN CTE cte
ON sac.Airline + CAST(sac.FlightNumber AS VARCHAR) + sac.Suffix = cte.Carrier + CAST(cte.FlightNumber AS VARCHAR) + cte.Suffix
AND sac.DepartureDate = cte.ScheduledDepartureDate
PLEASE TRY THIS.
SELECT Flight,
DepartureDate,
DepartureAirport,
CREWBASE,
SUM(CASE WHEN CREWTYPE = 'F' THEN 1 ELSE 0 END) AS CabinCrew ,
SUM(CASE WHEN CREWTYPE = 'C' THEN 1 ELSE 0 END) AS CockpitCrew
FROM #Table
GROUP BY Flight, DepartureDate, DepartureAirport, CREWBASE
Please Try This:
select Flight, DepartureDate, DepartureAirport,CREWBASE,
count(case when CREWTYPE='F' then 1 end ) as CabinCrew,count(case when CREWTYPE='C' then 1 end ) as CockpitCrew
from Staging.SabreAssignedCrew
group by Flight, DepartureDate, DepartureAirport,CREWBASE

Subquery within SubQuery in SQL - DB2

I am having issue when trying to make a the sub query shown in the first filter dynamically based on one of the results returned from the query. Can someone please tell me what I am doing wrong. In the first subquery it worked.
( SELECT
MAX( MAX_DATE - MIN_DATE ) AS NUM_CONS_DAYS
FROM
(
SELECT
MIN(TMP.D_DAT_INDEX_DATE) AS MIN_DATE,
MAX(TMP.D_DAT_INDEX_DATE) AS MAX_DATE,
SUM(INDEX_COUNT) AS SUM_INDEX
FROM
(
SELECT
D_DAT_INDEX_DATE,
INDEX_COUNT,
D_DAT_INDEX_DATE - (DENSE_RANK() OVER(ORDER BY D_DAT_INDEX_DATE)) DAYS AS G
FROM
DWH.MQT_SUMMARY_WATER_READINGS
WHERE
N_COD_METER_CNTX_KEY = 79094
) AS TMP
GROUP BY
TMP.G
ORDER BY
1
) ) AS MAX_NUM_CONS_DAYS
Above is the subquery I am trying to replace 123456 with CTXTKEY or CTXT.N_COD_METER_CNTX_KEY from query. Below is the full code. Please note than in the subquery before "MAX_NUM_CONS_DAYS" it worked. However, it was only one subquery down.
SELECT
N_COD_WM_DWH_KEY,
V_COD_WM_SN_2,
N_COD_SP_ID,
CTXKEY,
V_COD_MIU_SN,
N_COD_POD,
MIU_CAT,
V_COD_SITR_ASSOCIATED,
WO_INST_DATE,
WO_MIU_CAT,
DAYSRECEIVED3,
MAX_NUM_CONS_DAYS,
( CASE WHEN ( DAYSRECEIVED3 = 3 ) THEN 'Y' ELSE 'N' END ) AS GREEN,
( CASE WHEN ( DAYSRECEIVED3 < 3 AND DAYSRECEIVED3 > 0 ) THEN 'Y' ELSE 'N' END ) AS BLUE,
( CASE WHEN ( DAYSRECEIVED3 = 0 AND MAX_NUM_CONS_DAYS >= 5 ) THEN 'Y' ELSE 'N' END ) AS ORANGE,
( CASE WHEN ( DAYSRECEIVED3 = 0 AND MAX_NUM_CONS_DAYS BETWEEN 1 and 4 ) THEN 'Y' ELSE 'N' END ) AS RED
FROM
(
SELECT
WMETER.N_COD_WM_DWH_KEY,
WMETER.V_COD_WM_SN_2,
WMETER.N_COD_SP_ID,
CTXT.N_COD_METER_CNTX_KEY AS CTXKEY,
CTXT.V_COD_MIU_SN,
CTXT.N_COD_POD,
MIU.N_COD_MIU_CATEGORY AS MIU_CAT,
CTXT.V_COD_SITR_ASSOCIATED,
T1.D_DAT_PLAN_INST AS WO_INST_DATE,
T1.N_COD_MIU_CATEGORY AS WO_MIU_CAT,
( SELECT COUNT( DISTINCT D_DAT_INDEX_DATE ) FROM DWH.MQT_SUMMARY_WATER_READINGS WHERE ( N_COD_METER_CNTX_KEY = CTXT.N_COD_METER_CNTX_KEY ) AND D_DAT_INDEX_DATE BETWEEN ( '2013-07-10' ) AND ( '2013-07-12' ) ) AS DAYSRECEIVED3,
( SELECT
MAX( MAX_DATE - MIN_DATE ) AS NUM_CONS_DAYS
FROM
(
SELECT
MIN(TMP.D_DAT_INDEX_DATE) AS MIN_DATE,
MAX(TMP.D_DAT_INDEX_DATE) AS MAX_DATE,
SUM(INDEX_COUNT) AS SUM_INDEX
FROM
(
SELECT
D_DAT_INDEX_DATE,
INDEX_COUNT,
D_DAT_INDEX_DATE - (DENSE_RANK() OVER(ORDER BY D_DAT_INDEX_DATE)) DAYS AS G
FROM
DWH.MQT_SUMMARY_WATER_READINGS
WHERE
N_COD_METER_CNTX_KEY = 79094
) AS TMP
GROUP BY
TMP.G
ORDER BY
1
) ) AS MAX_NUM_CONS_DAYS
FROM DWH.DWH_WATER_METER AS WMETER
LEFT JOIN DWH.DWH_WMETER_CONTEXT AS CTXT
ON WMETER.N_COD_WM_DWH_KEY = CTXT.N_COD_WM_DWH_KEY
LEFT JOIN DWH.DWH_MIU AS MIU
ON CTXT.V_COD_MIU_SN = MIU.V_COD_MIU_SN
LEFT JOIN
( SELECT V_COD_CORR_WAT_METER_SN, D_DAT_PLAN_INST, N_COD_MIU_CATEGORY
FROM DWH.DWH_ORDER_MANAGEMENT_FACT
JOIN DWH.DWH_MIU
ON DWH.DWH_ORDER_MANAGEMENT_FACT.V_COD_MIU_SN = DWH.DWH_MIU.V_COD_MIU_SN
) AS T1
ON WMETER.V_COD_WM_SN_2 = T1.V_COD_CORR_WAT_METER_SN
WHERE
( V_COD_SITR_ASSOCIATED = 'X' )
AND ( ( MIU.N_COD_MIU_CATEGORY <> 4 ) OR ( ( MIU.N_COD_MIU_CATEGORY IS NULL ) AND ( ( T1.N_COD_MIU_CATEGORY <> 4 ) OR ( T1.N_COD_MIU_CATEGORY IS NULL ) ) ) )
)
Error I am getting is:
Error Code: -204, SQL State: 42704
I would say that a good option here would be to use a CTE, or Common Table Expression. You can do something similar to the following:
WITH CTE_X AS(
SELECT VAL_A
,VAL_B
FROM TABLE_A)
,CTE_Y AS(
SELECT VAL_C
,VAL_B
FROM TABLE_B)
SELECT VAL_A
,VAL_B
FROM CTE_X X
JOIN CTE_Y Y
ON X.VAL_A = Y.VAL_C;
While this isn't specific to your example, it does show that CTE's create a sort of temporary "in memory" table that you can access in a subsequent query. This should allow you to issue your inner two subselects as a CTE, and then use the CTE in the "SELECT MAX( MAX_DATE - MIN_DATE ) AS NUM_CONS_DAYS" query.
You cannot reference columns from the outer select in the subselect, no more than 1 level deep anyway. If I correctly understand what you're doing, you'll probably need to join DWH.MQT_SUMMARY_WATER_READINGS and DWH.DWH_WMETER_CONTEXT in the outer select.

Calculating using Variables in MYSQL query

hope you can help, this is driving me up the wall
I need to calculate the percentage of times a question has been failed, but this needs to be narrowed down by the geographical area, and product these questions are being asked against.
I have :
$CA002 = "( SELECT ROUND(100 * (SELECT count(CA002Result) from Data_Table where (CA002Result='Fail'))/count(CA002Result),2) from Data_Table) AS 'CA002 %'";
Which 'works' but just calculates against the whole set of records as an 'overall'
I'm trying :
$CA001 = "( SELECT ROUND(100 * (SELECT count(CA001Result) from Data_Table where (CA001Result='Fail' AND Area ='$Area'))/count(CA001Result) from Data_Table WHERE (Area='$Area'),2) AS 'CA001 %'";
And Also :
$CA001 = "( SELECT ROUND(100 * (SELECT count(CA001Result ) from Data_Table where (CA001Result='Fail' AND Product='$product' AND Area='$Area'))
/ count(CA001Result WHERE Product = '$product' AND Area='$Area'),2) from Data_Table) AS 'CA001 %'";
and am just getting errors no matter what I try, I just can't seem to work out what I need to put where.
Any great GREATLY apprteciated, thankyou.
Try this
//Filter by Area
create table t( id int, answer varchar(10),Area varchar(10));
insert into t select 1 , 'pass' , 'Area1';
insert into t select 2 , 'pass' , 'Area1';
insert into t select 3 , 'fail' , 'Area1';
insert into t select 4 , 'fail' , 'Area1';
insert into t select 5 , 'fail' , 'Area1';
insert into t select 6 , 'fail' , 'Area2';
SELECT
(x.TotalFailedAnswerRecord * 100) /y.TotalRecord AS Fail_percent
FROM
( SELECT Area,TotalFailedAnswerRecord = COUNT(answer)
FROM t
WHERE answer='fail' AND Area = 'Area1'
GROUP BY Area
)x
INNER JOIN
( SELECT Area,TotalRecord = COUNT(answer)
FROM t
WHERE Area = 'Area1'
GROUP BY Area
)y ON x.Area =y.Area
//Result
Fail_percent
-------------
60
//Filter by Area,Product
create table t( id int, answer varchar(10),Area varchar(10),Product varchar(10));
insert into t select 1 , 'pass' , 'Area1' ,'Product1';
insert into t select 2 , 'fail' , 'Area1' ,'Product1';
insert into t select 3 , 'fail' , 'Area1' ,'Product1';
insert into t select 4 , 'fail' , 'Area1' ,'Product1';
insert into t select 5 , 'fail' , 'Area1' ,'Product2';
insert into t select 6 , 'fail' , 'Area2' ,'Product2';
SELECT
(x.TotalFailedAnswerRecord * 100) /y.TotalRecord AS Fail_percent
FROM
( SELECT Area,Product,TotalFailedAnswerRecord = COUNT(answer)
FROM t
WHERE answer='fail' AND Area = 'Area1' AND Product = 'Product1'
GROUP BY Area,Product
)x
INNER JOIN
( SELECT Area,Product,TotalRecord = COUNT(answer)
FROM t
WHERE Area = 'Area1' AND Product = 'Product1'
GROUP BY Area,Product
)y ON x.Area =y.Area AND x.Product = y.Product
//Result
Fail_percent
-------------
75
Hope this helps