SQL WHERE statement returning both or conditions - sql

I'm trying to return a single row based on this where statement
WHERE
(C.id = G.community_id
AND P.service_type_id = G.service_type_id
AND I.unit_class_id = G.unit_class_id)
OR
(C.id = G.community_id
AND P.service_type_id = G.service_type_id)
The issue is I have to get a row based on multiple criteria and the more that match determines the final match. The statement above returns a row just fine if it matches the bottom or statement, but if it matches the first OR it returns results for both statements.
LIMIT 1 doesn't work either as sometimes it gives preference to the wrong result.
EDIT:
community_id
service_type_id
unit_class_id
1
1
1
1
1
null
Because of the way the table is both rows are true, my understanding was SQL took the first one that was true and returned it.
I apologize for not a lot of info I was hoping maybe there was just a bit of info I was missing. Here is my query.
CREATE VIEW view_invoice_line_item_gl_code
AS
SELECT
DISTINCT(ILI.invoice_line_item_id) AS invoice_line_item_id,
C.community_id AS community_id,
S.service_type_id AS service_type_id,
U.unit_class_id AS unit_class_id,
LIP.line_item_provider_id AS line_item_provider_id,
(SELECT gl_code_id
FROM gl_code G
WHERE (C.community_id = G.community_id
AND P.service_type_id = G.service_type_id)
AND ((G.unit_class_id IS NULL
AND G.line_item_provider_id IS NULL)
OR
(I.unit_class_id = G.unit_class_id
AND G.line_item_provider_id IS NULL)
OR
(I.unit_class_id = G.unit_class_id
AND ILI.line_item_provider_id = G.line_item_provider_id)
)) AS gl_code_id
FROM
invoice I
JOIN
invoice_line_item ILI ON (ILI.invoice_id = I.invoice_id)
JOIN
invoice_header IH ON (I.invoice_header_id = IH.invoice_header_id)
JOIN
provider_community_account PC ON (I.provider_community_account_id = PC.provider_community_account_id)
JOIN
line_item_provider LIP ON (ILI.line_item_provider_id = LIP.line_item_provider_id)
JOIN
unit_class U ON (I.unit_class_id = U.unit_class_id)
JOIN
community C ON (PC.community_id = C.community_id)
JOIN
provider P ON (PC.provider_id = P.provider_id)
JOIN
service_type S ON (P.service_type_id = S.service_type_id)

I'm assuming that you want to get the record that matches the most conditions first. One way to do that is to order by the number of matching conditions (in this case only one condition is different):
SELECT TOP 1 ...
FROM ...
WHERE
C.id = G.community_id
AND P.service_type_id = G.service_type_id
ORDER BY CASE WHEN I.unit_class_id = G.unit_class_id THEN 1 ELSE 0 END DESC

The first condition implies the second, so you can simplify it like this:
WHERE
C.id = G.community_id
AND P.service_type_id = G.service_type_id
You say where (A AND B) OR A so where A is sufficient.

You'll need to compute a "score" somehow. If you consider each predicate awards 1 point, then you could do something like:
select *
from (
select *,
case when <predicate1> then 1 else 0 end +
case when <predicate2> then 1 else 0 end as score
from t
WHERE
(C.id = G.community_id
AND P.service_type_id = G.service_type_id
AND I.unit_class_id = G.unit_class_id
)
OR
(
C.id = G.community_id
AND P.service_type_id = G.service_type_id
)
)
ORDER BY score DESC
LIMIT 1

Related

Conditionally adding a column in a SQL query

I'm trying to add a conditional SELECT column in a query and I'm having trouble writing it out:
SELECT v.GLTypeID,
v.something,
v.somethignElse,
CASE WHEN (SELECT TOP 1 Value FROM InterfaceParam WHERE InterfaceId = 0 AND Descr = 'gf') = 1 THEN a.CreditID ELSE NULL END AS CreditMemoID
FROM vGLDetails2 v
....
LEFT OUTER JOIN AssociationFund f
ON v.FundID = f.FundID
LEFT JOIN dbo.APLedger a ON v.RelID = a.APLedgerID AND v.RelTypeID IN (39, 40)
....
ORDER BY v.Code;
The query above works, however if the CASE statement is still returning an additional column regardless of the result of the subquery. How can I remove it if the subquery doesn't return a row?
How can I do this?
Change the location of AS. For example:
SELECT v.GLTypeID,
v.something,
v.somethignElse,
CASE WHEN (
SELECT TOP 1 Value
FROM InterfaceParam
WHERE InterfaceId = 0 AND Descr = 'creditMemo') = 1
THEN a.CreditID -- AS is not valid here
END AS CreditMemoID -- AS is valid here
FROM vGLDetails2 v
....
LEFT OUTER JOIN AssociationFund f
ON v.FundID = f.FundID
LEFT JOIN dbo.APLedger a ON v.RelID = a.APLedgerID AND v.RelTypeID IN (39, 40)
....
ORDER BY v.Code;
Note: I removed ELSE NULL since this is the default behavior of CASE.

Return a Count of 0 When No Rows

OK, I've looked this up and tried a number of solutions, but can't get it to work. I'm a bit of a novice. Here's my original query - how can I get it to return 0 for an account when there are no results in the student table?
SELECT a.NAME
,count(s.student_sid)
FROM account a
JOIN inst i ON a.inst_sid = i.root_inst_sid
JOIN inst_year iy ON i.inst_sid = iy.inst_sid
JOIN student s ON iy.inst_year_sid = s.inst_year_sid
WHERE s.demo = 0
AND s.STATE = 1
AND i.STATE = 1
AND iy.year_sid = 16
AND a.account_sid IN (
20187987
,20188576
,20188755
,52317128
,20189249
)
GROUP BY a.NAME;
Use an outer join, moving the condition on that table into the join:
select a.name, count(s.student_sid)
from account a
join inst i on a.inst_sid = i.root_inst_sid
join inst_year iy on i.inst_sid = iy.inst_sid
left join student s on iy.inst_year_sid = s.inst_year_sid
and s.demo = 0
and s.state = 1
where i.state = 1
and iy.year_sid = 16
and a.account_sid in (20187987, 20188576, 20188755, 52317128, 20189249)
group by a.name;
count() does not count null values, which s.student_sid will be if no rows join from student.
You need to LEFT JOIN and then SUM() over the group where s.student_sid is not null:
select
a.name,
sum(case when s.student_sid is null then 0 else 1 end) as student_count
from account a
join inst i on a.inst_sid = i.root_inst_sid
join inst_year iy on i.inst_sid = iy.inst_sid
left join student s
on iy.inst_year_sid = s.inst_year_sid
and s.demo = 0
and s.state = 1
where i.state = 1
and iy.year_sid = 16
and a.account_sid in (20187987, 20188576, 20188755, 52317128, 20189249)
group by a.name;
This is assuming that all of the fields in the student table that you are filtering on are optional. If you don't want to enforce removal of records where, say, s.state does not equal 1, then you need to move the s.state=1 predicate into the WHERE clauses.
If, for some reason, you are getting duplicate student IDs and students are being counted twice, then you can change the aggregate function to this:
count(distinct s.student_id) as student_count
...which is safe to do as count(distinct ...) ignores null values.

Not able to optimize a SQL Query. Taking huge cost. Oracle Apps

This is a query which I have to use as part of extracting Receipts based on certain conditions from Oracle 11i as a part of Conversion.
--> One important check is to check for invoices on hold. I just need to pull the details wherein the invoices are on hold. And the condition for checking is
In AP_HOLDS_ALL table -- 1) the invoice should exist
2) release lookup code should be NULL
3) status flag should be S or NULL and
4) there should not exist any line in AP_HOLDS_ALL table with same invoice ID with release lookup code as not null.
I have tried and added the below criteria in last of the following query, but it fetches the rows very very slow (100 000 records in a day).
How to improve the performance?
select * -- multiple Columns
from rcv_shipment_headers rsh,
rcv_shipment_lines rsl,
rcv_transactions rt,
hr_operating_units hou,
po_headers_all poh,
po_lines_all pol,
po_line_locations_all pll,
po_distributions_all pda,
po_vendors pv,
po_vendor_sites_all pvs
where 1 = 1
and rsh.shipment_header_id = rsl.shipment_header_id
and rsh.shipment_header_id = rt.shipment_header_id
and rsl.shipment_line_id = rt.shipment_line_id
and rt.po_header_id = poh.po_header_id
and rt.po_line_id = pol.po_line_id
and rt.po_line_location_id = pll.line_location_id
and rt.po_distribution_id = pda.po_distribution_id
and poh.po_header_id = pol.po_header_id
and pol.po_line_id = pll.po_line_id
and pll.line_location_id = pda.line_location_id
and poh.org_id = hou.organization_id
and poh.type_lookup_code = 'STANDARD'
and poh.authorization_status = 'APPROVED'
and poh.approved_flag = 'Y'
and rsh.ship_to_org_id = pll.ship_to_organization_id
and rt.organization_id = pll.ship_to_organization_id
and pol.org_id = hou.organization_id
and pll.org_id = hou.organization_id
and pda.org_id = hou.organization_id
and hou.date_to is null
and (rt.transaction_type = 'DELIVER' or rt.transaction_type = 'RECEIVE')
and rt.vendor_site_id = pvs.vendor_site_id
and rt.vendor_id = pv.vendor_id
and pv.vendor_id = pvs.vendor_id
and (nvl(pda.quantity_ordered, 0) - nvl(pda.quantity_cancelled, 0)) > 0
and nvl(pda.quantity_delivered, 0) > 0
and nvl(pda.quantity_billed, 0) > 0
and nvl(rsl.quantity_received, 0) > 0
and ((nvl(pda.quantity_delivered, 0) = nvl(pda.quantity_billed, 0)) or
(nvl(pda.quantity_delivered, 0) > nvl(pda.quantity_billed, 0)) or
(nvl(pda.quantity_delivered, 0) < nvl(pda.quantity_billed, 0)))
and exists
(select aida.po_distribution_id
from ap_invoices_all aia, ap_invoice_distributions_all aida
where aia.cancelled_date is null
and aida.po_distribution_id = pda.po_distribution_id
and exists
(select c.invoice_id
from ap_holds_all c
where c.release_lookup_code is null
and c.invoice_id = aia.invoice_id
and c.org_id = nvl(p_leg_operating_unit, c.org_id)
and (c.status_flag = 'S' or c.status_flag is null)
and not exists
(select 1
from ap_holds_all d
where d.invoice_id = c.invoice_id
and d.org_id = nvl(p_leg_operating_unit, d.org_id)
and d.release_lookup_code is not null))
and aia.org_id = nvl(p_leg_operating_unit, aia.org_id)
and aia.invoice_id = aida.invoice_id)
and poh.org_id = nvl(p_leg_operating_unit, poh.org_id)
p_leg_operating_unit is a parameter which is having NULL value as I am trying to get the values for all the OU's
** last exists is causing the issue.
Try with the following , may solve your issue :
/*+ parallel(4) */ --hint. If doesnt work , then try with
parallel(8)/parallel(16).
Reorder the joins . Join the tables based on the least number of rows returned. FOr example Table A,B,C . Join a & b returns 100
rows, but B&c returns 20 rows. then First join B & C table and join
with A.
Use /*+ Index * hint if optimizer doesn't access indexes.

All rows where at least one child has all of its own children pass a condition

I'm having a little trouble with a SQL query, and thought I'd solicit the wisdom of the crowd to see what I'm missing. I'm pretty sure the below works, but it seems really poor and I'm wondering if there's a smarter way (ideally using joins instead of sub-selects) to do this.
The Problem
Let's say I have some tables:
Prize
- PrizeId
RulePrize_Map
- PrizeId
- RuleId
Rule
- RuleId
Conditional
- ConditionalId
- RuleId
- InputId
- ExpectedValue (bit)
Input
- InputId
A Prize is won when at least one Rule is true. A Rule is true when all of its Conditionals are true. A Conditional is "true" when its InputId is either present or not present in the Input table, as designated by the ExpectedValue field. This could perhaps be treated as equivalent to: Count(InputId in Input table) = ExpectedValue for the Conditional's InputId.
Some Examples:
Conditional (InputId = 11, ExpectedValue = 1) -> True if InputId 11 in Input Table
Conditional (InputId = 12, ExpectedValue = 0) -> True if Inputid 12 NOT in Input Table
My Goal
I want to get all Prizes where at least one Rule is "true". I would settle for: "All Rules that are true".
My Attempt
select p.PrizeId from Prize p INNER JOIN RulePrize_Map rpm ON rpm.PrizeId = p.PrizeId
WHERE p.PrizeId IN
(select r.PrizeId from Rule r
where
(select count(*) from Conditional c1 where c1.RuleId = r.RuleId)
=
(select count(*) from Conditional c2
where c2.RuleId = r.RuleId AND
(select count(*) from Input i where i.InputId = c2.InputId) = c2.ExpectedValue
)
)
GROUP BY p.prizeId
The question change a bit, so I have redone the answer...
SELECT
PrizeId
FROM
(
SELECT
PrizeRule_Map.PrizeId,
PrizeRule_Map.RuleId
FROM
PrizeRule_Map
INNER JOIN
Rule
ON Rule.RuleId = PrizeRule_Map.RuleId
INNER JOIN
Conditional
ON Conditional.RuleId = Rule.RuleID
LEFT JOIN
Input
ON Input.InputId = Conditional.InputID
GROUP BY
PrizeRule_Map.PrizeId,
PrizeRule_Map.RuleId
HAVING
COUNT(*) = SUM(CASE Conditional.ExpectedValue
WHEN 1 THEN CASE WHEN Input.InputId IS NULL THEN 0 ELSE 1 END
WHEN 0 THEN CASE WHEN Input.InputId IS NULL THEN 1 ELSE 0 END
END
)
)
AS map
GROUP BY
PrizeId
To get all RuleIds where ALL Conditionals are true:
SELECT r.RuleID
FROM Rule r
JOIN Conditional c
ON c.RuleId = r.RuleId
LEFT JOIN Input i
ON i.InputId = c.InputId
GROUP BY r.RuleID
HAVING COUNT( CASE WHEN (c.ExpectedValue=1) AND (i.InputId IS NOT NULL)
OR (c.ExpectedValue=0) AND (i.InputId IS NULL)
THEN 1
ELSE NULL
END )
= COUNT( * )
Another way - probably slower but it doesn't hurt to test for speed. It doesn't use CASE but the difference (EXCEPT) of two JOINs, only one of them using GROUP BY:
SELECT r.RuleID
FROM Rule r
JOIN Conditional c
ON c.RuleId = r.RuleId
LEFT JOIN Input i
ON i.InputId = c.InputId
WHERE c.ExpectedValue = 1
GROUP BY r.RuleID
HAVING COUNT( i.InputId ) = COUNT( * )
EXCEPT
SELECT r.RuleID
FROM Rule r
JOIN Conditional c
ON c.RuleId = r.RuleId
JOIN Input i
ON i.InputId = c.InputId
WHERE c.ExpectedValue = 0
Try the following:
SELECT Rule.RuleId, Rule.RuleName
FROM Rule
INNER JOIN Conditional ON Rule.RuleId = Conditional.RuleId
Where Conditional.ExpectedValue == true

order by first occurence of returned results

I have two tables and want to get technology_tag from table b based on reference id from table a:
select b.dbid, b.technology_tag
from tblConnect a, tblSites b
where a.Site_DBID = 2
and a.Related_Site_DBID = 1
and (b.dbid = a.bsc_tag_dbid or b.dbid = a.related_bsc_dbid or b.dbid = a.related_msc_dbid)
What I want to have here is to order the returned rows based on first occurrence (in where clause)
1st- b.dbid = a.bsc_tag_dbid
2cnd- b.dbid = a.related_bsc_dbid
3rd- b.dbid = a.related_msc_dbid
Does anyone has a clue how to do that?
First, you should switch to using actual JOIN clauses when performing joins. That said, this ORDER BY clause should do what you want:
SELECT
B.dbid,
B.technology_tag
FROM tblConnect A
INNER JOIN tblSites B ON
B.dbid IN (A.bsc_tag_dbid, A.related_bsc_dbid, A.related_msc_dbid)
WHERE
A.Site_DBID = 2 AND
A.Related_Site_DBID = 1
ORDER BY
CASE
WHEN B.dbid = A.bsc_tag_dbid THEN 1
WHEN B.dbid = A.related_bsc_dbid THEN 2
WHEN B.dbid = A.related_msc_dbid THEN 3
ELSE 4 -- Not really necessary, but I always use an ELSE when I use CASE
END