select only one value in 1:N relation - sql

i want to have only one value in the result of the query which is the first value, or the last value, i tried many things but i coudnt resolve it, the query is too long but i picked for you only the part where i am stucked.
select eccev.extra_data , c.id,
case when (eccev.extra_data::json->'tns')::VARCHAR = 'false'
then 'NON'
else case when coalesce((eccev.extra_data::json->'tns')::VARCHAR, '') = '' then 'EMPTY VALUE' else 'OUI'
end end as tns
from endorsement_contract_covered_element_version eccev, endorsement_contract_covered_element ecce, endorsement_contract ec, contract c, endorsement e, party_party pp
WHERE ec.endorsement = e.id
and e.applicant = pp.id
and c.subscriber = pp.id
AND eccev.covered_element_endorsement = ecce.id
and ecce.contract_endorsement = ec.id
and c.contract_number = 'CT20200909112'
with this query i have the result
{"qualite":"non_etu","tns":false} 199479 NON
{"qualite":"non_etu","tns":false} 199479 NON
{"qualite":"non_etu","tns":false} 199479 NON
i want to have only the first or the last row so i dont have repetition on the other rows, i saw that we can use first_value(X over (XX)) but i couldnt make it.
if u guys can help me, i would be gratefull
Thanks

you can try this
select distinct on (eccev.extra_data , c.id) eccev.extra_data , c.id, case when ...
but your query seems not optimized as you cross join 6 tables all together ...

Related

unable to get data from the tables when applied where condition

Unable to get the data from the table after applying where conditio0n. manually checked all the tables the data is present in it.
Need help in resolving this issue.
I tried changing the where condition but still unable to get the data.
I assume the issue is in below condition however I'm unable to identify it
Below is the code:
SELECT
a.OpportunityCode AS KPMG_Opportunity__c,
CompetitorCode AS Account__c,
CASE
WHEN
b.StageDescription = 'Won'
THEN
'True'
ELSE
'False'
END
AS KPMG_Won_Opportunity__c, c.ConvertedOutcomeReasonCode, b.CloseDate, b.etl_rec_eff_end_ts, d.IsArchived
FROM
bpg_crm_opportunity_refined.oppty_competitors AS a
LEFT JOIN
bpg_crm_opportunity_refined.oppty_header AS b
ON a.opportunitycode = b.OpportunityCode
LEFT JOIN
bpg_oppty_mgmt_trusted.outcomereason_conversion_lkp c
ON b.OpportunityStatusCode_Orig = c.StatusCode
LEFT JOIN
bpg_crm_engagement_trusted.edw_dim_entity d
ON b.PrimaryAccountCode = d.EntityID
WHERE
d.IsArchived != 'false'
and c.ConvertedOutcomeReasonCode != 'Z004A'
and date_part('Year', b.etl_rec_eff_end_ts) = '9999'
Unable to get the data from the table after applying where conditio0n. manually checked all the tables the data is present in it.
Need help in resolving this issue.
I tried changing the where condition but still unable to get the data.
I assume the issue is in below condition however I'm unable to identify it
SELECT
a.OpportunityCode AS KPMG_Opportunity__c,
CompetitorCode AS Account__c,
CASE
WHEN
b.StageDescription = 'Won'
THEN
'True'
ELSE
'False'
END
AS KPMG_Won_Opportunity__c,
c.ConvertedOutcomeReasonCode, b.CloseDate, b.etl_rec_eff_end_ts, d.IsArchived
FROM
bpg_crm_opportunity_refined.oppty_competitors AS a
LEFT JOIN
(
SELECT OpportunityCode,OpportunityStatusCode_Orig,PrimaryAccountCode,
StageDescription,CloseDate,etl_rec_eff_end_ts
FROM bpg_crm_opportunity_refined.oppty_header
WHERE b.etl_rec_eff_end_ts BETWEEN '99990101'AND '99991231'
)AS b ON a.opportunitycode = b.OpportunityCode
LEFT JOIN
(
SELECT ConvertedOutcomeReasonCode,StatusCode
FROM
bpg_oppty_mgmt_trusted.outcomereason_conversion_lkp c
WHERE ConvertedOutcomeReasonCode != 'Z004A'
)AS c ON b.OpportunityStatusCode_Orig = c.StatusCode
LEFT JOIN
(
SELECT EntityID,IsArchived
FROM
bpg_crm_engagement_trusted.edw_dim_entity
WHERE IsArchived != 'false'
) D ON b.PrimaryAccountCode = d.EntityID
May be something like this

Sorry I need to hide

Elon Reeve Musk FRS is an entrepreneur and business magnate. He is the founder, CEO, and Chief Engineer at SpaceX; early-stage investor, CEO, and Product Architect of Tesla, Inc.; founder of The Boring Company; and co-founder of Neuralink and OpenAI.
Your inner select returns a table. That can't be used as parameter to match a WHERE IN condition. Instead try using an INNER JOIN
sum(decode(
select sum(dou.noukn)
from dou
join v_kzeiritsu on
dou.zeiritsu = v_kzeiritsu.zeiritsu
)) as noukn2;
Just move your sum logic inside select as follows:
(SELECT SUM(DOU$2.NOUKN)
FROM SDNISHI.V_KZEIRITSU V
WHERE DOU$2.ZEIRITSU = V.ZEIRITSU) AS NOUKN2
In case If it gives aggregation error then use sum(above query) AS NOUKN2
Your code is very strange. For instance, it seems to assume that V_KZEIRITSU has one row. But, you can move this to the FROM clause:
SELECT SUM(CASE WHEN DOU.ZEIRITSU = K.ZEIRITSU THEN DOU.NOUKN ELSE 0 END) AS NOUKN2
FROM DOU LEFT JOIN
V_KZEIRITSU K
ON 1=1 -- in case the table is really empty
A slightly more reasonable version would be:
SELECT SUM(DOU.NOUKN) AS NOUKN2
FROM DOU LEFT JOIN
V_KZEIRITSU K
ON DOU.ZEIRITSU = K.ZEIRITSU -- in case the table is really empty
It seems rather unlikely to me that this is what you really intend. If not, I would suggest that you ask a new question with appropriate same data, desired results, and explanation of the results. A non-working query should not be expected to provide the same level of information.
I'd say that it is, actually, as simple as
select sum(dou.noukn)
from dou
where dou.zeiritsu in (select zeiritsu from v_kzeiritsu)
(I'm not sure what dou is (table? alias?), but I hope you do.)
After you edited the question, I'm editing the answer. I marked with "--> this" two lines that - in my opinion - might help. As previously, the whole sum(case ...) as noukn2 is replaced by a simple sum(dou$2.noukn).
Note that - in Oracle - you can't use as keyword for table alias. For example:
no: from employees as e
yes: from employees e
Here's your query:
SELECT DOU$2.CUSTCD AS CUSTCD,
DOU$2.CHUNO AS CHUNO,
DOU$2.LINNO AS LINNO,
DOU$2.SHIPDAYYM AS SHIPDAYYM,
SUM (DOU$2.NOUKN) AS NOUKN,
SUM (DOU$2.ZEIKN) AS ZEIKN,
SUM (dou$2.noukn) AS noukn2 --> this
FROM SDNISHI.T_HCHUMON_DOUSOU DOU$2
INNER JOIN SDNISHI.SY_KANRI KNR ON KNR.SHIPDAYYM = DOU$2.SHIPDAYYM
INNER JOIN SDNISHI.T_HCHUMON_MEI MEI
ON MEI.CUSTCD = DOU$2.CUSTCD
AND MEI.CHUNO = DOU$2.CHUNO
AND MEI.LINNO = DOU$2.LINNO
AND MEI.SHIPDAYYM = DOU$2.SHIPDAYYM
AND MEI.USEDNGKBN = '0'
AND MEI.CANCELKBN = '0'
LEFT OUTER JOIN SDNISHI.T_HCHUMON_HD HD
ON HD.CUSTCD = MEI.CUSTCD
AND HD.CHUNO = MEI.CHUNO
AND HD.LINNO = MEI.LINNO
AND HD.USEDNGKBN = '0'
AND HD.CANCELKBN = '0'
AND isnull (HD.CANKBN, '00') = '00'
JOIN v_keziritsu vk ON vk.zeiritsu = dou$2.zeiritsu --> this
WHERE DOU$2.USEDNGKBN = '0'
AND DOU$2.CANCELKBN = '0'
AND ( ( MEI.CHGDELKBN = '1'
AND MEI.HDOUSOUKBN = '02'
AND ( MEI.CHUSU > 0
OR MEI.BCHUSU > 0))
OR ( MEI.CHGDELKBN != '1'
AND HD.HDOUSOUKBN = '02'
AND ( MEI.CHKBTNFGA = '1'
AND HD.CHUSU > 0)
OR ( MEI.CHKBTNFGB = '1'
AND HD.BCHUSU > 0)))
GROUP BY DOU$2.CUSTCD,
DOU$2.CHUNO,
DOU$2.LINNO,
DOU$2.SHIPDAYYM

Test Case for Triple Join in SQL

SELECT triple_join('A multiple join on the Equipment, EquipmentTypes, and
RentalInfo works effectively: ',
CASE WHEN
(SELECT name, e.riid, rental_start, in_use FROM Equipment AS e JOIN
EquipmentTypes ON equipment_type = etid JOIN RentalInfo AS ri ON
e.riid = ri.riid)
= ('Enabler 420', 1, '20141107', 1)
THEN 'Passed' ELSE 'Failed' END
);
This is the code that tests whether my join is working effectively. When I run the code, however, it says I have a syntax error near ",". Can someone tell me what's going on?
P.S.: The Equipment, EquipmentTypes, and RentalInfo are tables I have defined and 'inserted to' in another file.
Not sure if it solves the problem, but it is much simpler to debug than what you had. Also, it will solve the problem of multiple matching records:
SELECT triple_join('A multiple join on the Equipment, EquipmentTypes, and
RentalInfo works effectively: ',
CASE WHEN EXISTS (
SELECT TOP 1 1 FROM Equipment AS e
INNER JOIN EquipmentTypes as et ON e.equipment_type = et.etid
INNER JOIN RentalInfo AS ri ON e.riid = ri.riid
WHERE name = 'Enabler 420' and e.riid = 1 and
rental_start = '20141107' and in_use = 1)
THEN 'Passed' ELSE 'Failed' END
);
If problem still persist try to run separately internal "SELECT" and the function and see what is causing the problem.

Redshift SQL Case Statement and WHERE Clause not working

I'm running the following SQL script to create a table with information on which marketing efforts are driving people to my site for form fills.
The case statement for marketing source stamp does not work. My results still have values for search-brand-whatever for the marketing_source column when those values should now just read "google-adwords".
I'm also getting results with a createddate of 9/15/2015 and after when my filter clearly states createddate >= '1/1/2016'.
Any ideas?
create table temp.roi_inqs as (
Select
a.ID,
cast(a.createddate as date) as date,
CASE
WHEN a.marketing_source_stamp__c = 'search%' then 'google-adwords'
ELSE a.marketing_source_stamp__c
END AS marketing_source,
CASE
when a.contactid is null then b.email
when a.contactid is not null then c.email
end as prospect_email
from rjm_current.sf_campaignmember a
left join rjm_current.sf_lead b on b.id = a.leadid
left join rjm_current.sf_contact c on c.id = a.contactid
where cast(a.createddate as date) >= '1/1/2016'
AND (
campaign_marketing_type__c in ('A','C'))
OR
(campaign_marketing_type__c = 'B'
AND a.status in ('Registered','Attended','No Show')));
Your entire predicate is of the form
A AND B OR C
If you don't put any parentheses, this means you're querying
(A AND B) OR C
When you really meant to write
A AND (B OR C)
As a general rule: Always put parentheses if you're mixing AND and OR
#Lukas Eder Answered my question for the date issue.
For the case statement I had to change the marketing_source_stamp__c = 'search%' to marketing_source_stamp__c LIKE 'search%' and that issue is solved.
CASE
WHEN a.marketing_source_stamp__c LIKE 'search%' then 'google-adwords'
ELSE a.marketing_source_stamp__c
END AS marketing_source,

Oracle Sum Based On Condition

SQL first so I can reference it lower:
SELECT ID,
SUM(length(substr(DATA_STRING, instr(DATA_STRING,'P')+1)))
FROM DATA P, PLC PP
WHERE P.ID = PP.ID
AND instr(DATA_STRING, 'F') = 0
GROUP BY ID
The function above looks for the P in each data string and counts up how many characters are in the string.
So my problem is thus, I have two conditions that can occur, one where the data string could contain the P as in above, or when it contains a F. I need to be able to check for both and then sum up the total. The issue with the above is that I sum in a 0 if that condition when the string has an F occurs.
I almost need the equivalent of SUMIF in Excel so that I could say if when I search for P it's 0, then look for the F and add in that length and vice versa.
Please let me know if you have suggestions!
length(substr(DATA_STRING, instr(DATA_STRING,'P')+1))? This is doing a lot of work.
From what I can tell, you want sum of the number of characters after a 'P' or 'F' in the string. If so:
SELECT ID,
SUM(CASE WHEN data_string like '%P%'
THEN len(DATA_STRING) - (instr(DATA_STRING, 'P') + 1) ELSE 0
END) as Num_P,
SUM(CASE WHEN data_string like '%F%'
THEN len(DATA_STRING) - (instr(DATA_STRING, 'F') + 1) ELSE 0
END) as Num_F
FROM DATA P JOIN
PLC PP
ON P.ID = PP.ID
GROUP BY ID;
I also fixed the join syntax to use explicit joins.