select query with Not IN keyword - sql

I have two Tables as below..
tbPatientEncounter
tbVoucher
when i execute select query as below
Select EncounterIDP,EncounterNumber from tbPatientEncounter
it returens me 180 rows. and
Select VoucherIDP,EncounterIDF from tbVoucher
above query returns me 165 rows.
but i want to execute select query that returns me data like EncounterIDP not in tbVoucher, for that i have tried below Select query...
Select * from tbPatientEncounter pe
where pe.EncounterIDP not in
(Select v.EncounterIDF from tbVoucher v )
it doesn't returns any row. in first image it shows EncounterIDP 9 in tbPatientEncounter, but it not inserted in tbVoucher for that i have tried select Query like
Select * from tbVoucher where EncounterIDF = 9
it returns me 0 rows.
My question is what is wrong with my above Not In Query.?

In all likelihood, the problem is NULL values in tbVoucher. Try this:
Select *
from tbPatientEncounter pe
where pe.EncounterIDP not in (Select v.EncounterIDF
from tbVoucher v
where v.EncounterIDF is not NULL
)

Are you comparing the correct fields in tbVoucher?
Try using a left join
Select EncounterIDP,EncounterNumber from tbPatientEncounter
left join tbVoucher on EncounterIDP = EncounterIDF
where EncounterIDF is null

Call me a skeptic because I don't see anything wrong with your query. Is this really all in the query or did you simplify it for us?
Select * from tbPatientEncounter pe
where pe.EncounterIDP not in
(Select v.EncounterIDF from tbVoucher v )

Related

SQL Teradata TOP and DISTINCT

I'm trying to write a nested TOP + DISTINCT query in Teradata SQL. My query looks like this:
SELECT TOP 5
*
FROM
(SELECT DISTINCT k_name.KUNDE_NAME1
FROM DB_DWH_MART_AKM_PLT.VW_F_EVENT f_ev
INNER JOIN DBX_DWH_SBX_AKM_PRD.TB_KUNDE_EKP_NAME_AKTUELL k_name ON f_ev.AUFTRAGGEBER_EKP = k_name.EKP
WHERE f_ev.PROCESS_NO = 1075)
I get an error:
Expected something like a name or a Unicode delimited identifier... between ) and ;".
I don't know what I did wrong.
The DISTINCT query would execute correctly on its own.
Why not use a group by?
SELECT TOP 5 k_name.KUNDE_NAME1
FROM DB_DWH_MART_AKM_PLT.VW_F_EVENT f_ev
INNER JOIN DBX_DWH_SBX_AKM_PRD.TB_KUNDE_EKP_NAME_AKTUELL k_name ON f_ev.AUFTRAGGEBER_EKP = k_name.EKP
WHERE f_ev.PROCESS_NO = 1075
GROUP BY k_name.KUNDE_NAME1 --instead of using distinct
ORDER BY k_name.KUNDE_NAME1; --remove or modify as needed

Oracle SQL XOR condition with > 14 tables

I have a question on sql desgin.
Context:
I have a table called t_master and 13 other tables (lets call them a,b,c... for simplicity) where it needs to compared.
Logic:
t_master will be compared to table 'a' where t_master.gen_val =
a.value.
If record exist in t_master, retrieve t_master record, else retrieve 'a' record.
I do not need to retrieve the records if it exists in both tables (t_master and a) - XOR condition
Repeat this comparison with the remaining 12 tables.
I have some idea on doing this, using WITH to subquery the non-master tables (a,b,c...) first with their respective WHERE clause.
Then use XOR statement to retrieve the records.
Something like
WITH a AS (SELECT ...),
b AS (SELECT ...)
SELECT field1,field2...
FROM t_master FULL OUTER JOIN a FULL OUTER JOIN b FULL OUTER JOIN c...
ON t_master.gen_value = a.value
WHERE ((field1 = x OR field2 = y ) AND NOT (field1 = x AND field2 = y))
AND ....
.
.
.
.
Seeing that I have 13 tables that I need to full outer join, is there a better way/design to handle this?
Otherwise I would have at least 2*13 lines of WHERE clause which I'm not sure if that will have impact on the performance as t_master is sort of a log table.
**Assume I cant change any schema.
Currently I'm not sure if this SQL will working correctly yet, so I'm hoping someone can guide me in the right direction regarding this.
update from used_by_already's suggestion:
This is what I'm trying to do (comparison between 2 tables first, before I add more, but I am unable to get values from ATP_R.TBL_HI_HDR HI_HDR as it is in the NOT EXISTS subquery.
How do i overcome this?
SELECT LOG_REPO.UNIQ_ID,
LOG_REPO.REQUEST_PAYLOAD,
LOG_REPO.GEN_VAL,
LOG_REPO.CREATED_BY,
TO_CHAR(LOG_REPO.CREATED_DT,'DD/MM/YYYY') AS CREATED_DT,
HI_HDR.HI_NO R_VALUE,
HI_HDR.CREATED_BY R_CREATED_BY,
TO_CHAR(HI_HDR.CREATED_DT,'DD/MM/YYYY') AS R_CREATED_DT
FROM ATP_COMMON.VW_CMN_LOG_GEN_REPO LOG_REPO JOIN ATP_R.TBL_HI_HDR HI_HDR ON LOG_REPO.GEN_VAL = HI_HDR.HI_NO
WHERE NOT EXISTS
(SELECT NULL
FROM ATP_R.TBL_HI_HDR HI_HDR
WHERE LOG_REPO.GEN_VAL = HI_HDR.HI_NO
)
UNION ALL
SELECT LOG_REPO.UNIQ_ID,
LOG_REPO.REQUEST_PAYLOAD,
LOG_REPO.GEN_VAL,
LOG_REPO.CREATED_BY,
TO_CHAR(LOG_REPO.CREATED_DT,'DD/MM/YYYY') AS CREATED_DT,
HI_HDR.HI_NO R_VALUE,
HI_HDR.CREATED_BY R_CREATED_BY,
TO_CHAR(HI_HDR.CREATED_DT,'DD/MM/YYYY') AS R_CREATED_DT
FROM ATP_R.TBL_HI_HDR HI_HDR JOIN ATP_COMMON.VW_CMN_LOG_GEN_REPO LOG_REPO ON HI_HDR.HI_NO = LOG_REPO.GEN_VAL
WHERE NOT EXISTS
(SELECT NULL
FROM ATP_COMMON.VW_CMN_LOG_GEN_REPO LOG_REPO
WHERE HI_HDR.HI_NO = LOG_REPO.GEN_VAL
)
Full outer joins used to exclude all matching rows can be an expensive query. You don't supply much detail, but perhaps using NOT EXISTS would be simpler and maybe it will produce a better explain plan. Something along these lines.
select
cola,colb,colc
from t_master m
where not exists (
select null from a where m.keycol = a.fk_to_m
)
and not exists (
select null from b where m.keycol = b.fk_to_m
)
and not exists (
select null from c where m.keycol = c.fk_to_m
)
union all
select
cola,colb,colc from a
where not exists (
select null from t_master m where a.fk_to_m = m.keycol
)
union all
select
cola,colb,colc from b
where not exists (
select null from t_master m where b.fk_to_m = m.keycol
)
union all
select
cola,colb,colc from c
where not exists (
select null from t_master m where c.fk_to_m = m.keycol
)
You could union the 13 a,b,c ... tables to simplify the coding, but that may not perform so well.

Laravel 4.2 execute query without using elequent query builder

I have a query with sub-query .. and i want to write an explicite SQL request and execute it
Query :
select count(*) as count from
(
SELECT DISTINCT t.article_id FROM
`articles` as a left join `tags` as t
on a.`id` = t.`article_id`
where a.`flag` = 1
) as sub
i tried this to execute the request without building the query :
DB::connection()->getPdo()->exec( $sql );
But it always return 0 !
You can use sub query with DB::raw.
A method DB::raw() (don’t forget to use Illuminate\Support\Facades\DB) allows you to select whatever you want and basically write raw SQL statements.
DB::select(DB::raw("select count(*) as count from
(
SELECT DISTINCT t.article_id FROM
`articles` as a left join `tags` as t
on a.`id` = t.`article_id`
where a.`flag` = 1
) as sub"));
https://laravel.com/docs/4.2/queries#raw-expressions
Why don't you try with DB::raw('your sql query here')
Using DB::select should solve your problem.
DB::select('select count(*) as count from
(
SELECT DISTINCT t.article_id FROM
`articles` as a left join `tags` as t
on a.`id` = t.`article_id`
where a.`flag` = 1
) as sub');

subquery returning more than 1 values

SELECT user_info.s_name, user_info.name, user_info.f_name, user_info.usr_id, user_info.img_path, Village_master.v_nm
FROM Village_master
INNER JOIN User_reg_master ON Village_master.v_id = User_reg_master.v_id
INNER JOIN user_info ON User_reg_master.usr_id = user_info.usr_id
WHERE user_info.usr_id NOT LIKE #u_id
AND user_info.usr_id NOT LIKE (
SELECT pers_dict_master.pers_dict_ids
FROM pers_dict_ids
WHERE pers_dict_master.usr_id=#u_id
)
usr_id| pers_dict_usr_id
1 | 13
1 | 6
The problem you are facing is this ,
user_info.usr_id NOT LIKE
(SELECT pers_dict_master.pers_dict_ids
FROM pers_dict_ids
WHERE pers_dict_master.usr_id=#u_id)
This is your sub query
(SELECT pers_dict_master.pers_dict_ids
FROM pers_dict_ids
WHERE pers_dict_master.usr_id=#u_id)
It is fetching two columns.But In the LIKE command you are using a one Column.
So make it work USE NOT INCOMMAND
SELECT user_info.s_name,
user_info.name,
user_info.f_name,
user_info.usr_id,
user_info.img_path,
Village_master.v_nm
FROM Village_master
INNER JOIN User_reg_master ON Village_master.v_id = User_reg_master.v_id
INNER JOIN user_info ON User_reg_master.usr_id = user_info.usr_id
WHERE user_info.usr_id NOT LIKE #u_id
AND user_info.usr_id NOT IN
( SELECT pers_dict_master.pers_dict_ids
FROM pers_dict_ids
WHERE pers_dict_master.usr_id=#u_id )
You should probably include some more detail about your issue. Is the sub query expected to return more than one result? If so then you could simply use TOP(ie. select top 1 ...) to get just a single result and add an ORDER BY to the sub query if you want to get a certain sorted top value from that result set.
If the issue is that the sub query returns more than 1 result when it shouldn't, then your problem lies deeper. It looks like you may have meant to use IN for the subquery and for a different comparison, but it's difficult to tell. Perhaps you meant this?:
user_info.usr_id NOT IN
(SELECT pers_dict_master.pers_dict_ids
FROM pers_dict_ids WHERE pers_dict_master.usr_id=#u_id)

sql parameterised cte query

I have a query like the following
select *
from (
select *
from callTableFunction(#paramPrev)
.....< a whole load of other joins, wheres , etc >........
) prevValues
full join
(
select *
from callTableFunction(#paramCurr)
.....< a whole load of other joins, wheres , etc >........
) currValues on prevValues.Field1 = currValues.Field1
....<other joins with the same subselect as the above two with different parameters passed in
where ........
group by ....
The following subselect is common to all the subselects in the query bar the #param to the table function.
select *
from callTableFunction(#param)
.....< a whole load of other joins, wheres , etc >........
One option is for me to convert this into a function and call the function, but i dont like this as I may be changing the
subselect query quite often for.....or I am wondering if there is an alternative using CTE
like
with sometable(#param1) as
(
select *
from callTableFunction(#param)
.....< a whole load of other joins, wheres , etc >........
)
select
sometable(#paramPrev) prevValues
full join sometable(#currPrev) currValues on prevValues.Field1 = currValues.Field1
where ........
group by ....
Is there any syntax like this or technique I can use like this.
This is in SQL Server 2008 R2
Thanks.
What you're trying to do is not supported syntax - CTE's cannot be parameterised in this way.
See books online - http://msdn.microsoft.com/en-us/library/ms175972.aspx.
(values in brackets after a CTE name are an optional list of output column names)
If there are only two parameter values (paramPrev and currPrev), you might be able to make the code a little easier to read by splitting them into two CTEs - something like this:
with prevCTE as (
select *
from callTableFunction(#paramPrev)
.....< a whole load of other joins, wheres , etc
........ )
,curCTE as (
select *
from callTableFunction(#currPrev)
.....< a whole load of other joins, wheres , etc
........ ),
select
prevCTE prevValues
full join curCTE currValues on
prevValues.Field1 = currValues.Field1 where
........ group by
....
You should be able to wrap the subqueries up as parameterized inline table-valued functions, and then use them with an OUTER JOIN:
CREATE FUNCTION wrapped_subquery(#param int) -- assuming it's an int type, change if necessary...
RETURNS TABLE
RETURN
SELECT * FROM callTableFunction(#param)
.....< a whole load of other joins, wheres , etc ........
GO
SELECT *
FROM
wrapped_subquery(#paramPrev) prevValues
FULL OUTER JOIN wrapped_subquery(#currPrev) currValues ON prevValues.Field1 = currValues.Field1
WHERE ........
GROUP BY ....
After failing to assign scalar variables before with, i finally got a working solution using a stored procedure and a temp table:
create proc hours_absent(#wid nvarchar(30), #start date, #end date)
as
with T1 as(
select c from t
),
T2 as(
select c from T1
)
select c from T2
order by 1, 2
OPTION(MAXRECURSION 365)
Calling the stored procedure:
if object_id('tempdb..#t') is not null drop table #t
create table #t([month] date, hours float)
insert into #t exec hours_absent '9001', '2014-01-01', '2015-01-01'
select * from #t
There may be some differences between my example and what you want depending on how your subsequent ON statements are formulated. Since you didn't specify, I assumed that all the subsequent joins were against the first table.
In my example I used literals rather than #prev,#current but you can easily substitute variables in place of literals to achieve what you want.
-- Standin function for your table function to create working example.
CREATE FUNCTION TestMe(
#parm int)
RETURNS TABLE
AS
RETURN
(SELECT #parm AS N, 'a' AS V UNION ALL
SELECT #parm + 1, 'b' UNION ALL
SELECT #parm + 2, 'c' UNION ALL
SELECT #parm + 2, 'd' UNION ALL
SELECT #parm + 3, 'e');
go
-- This calls TestMe first with 2 then 4 then 6... (what you don't want)
-- Compare these results with those below
SELECT t1.N AS AN, t1.V as AV,
t2.N AS BN, t2.V as BV,
t3.N AS CN, t3.V as CV
FROM TestMe(2)AS t1
FULL JOIN TestMe(4)AS t2 ON t1.N = t2.N
FULL JOIN TestMe(6)AS t3 ON t1.N = t3.N;
-- Put your #vars in place of 2,4,6 adding select statements as needed
WITH params
AS (SELECT 2 AS p UNION ALL
SELECT 4 AS p UNION ALL
SELECT 6 AS p)
-- This CTE encapsulates the call to TestMe (and any other joins)
,AllData
AS (SELECT *
FROM params AS p
OUTER APPLY TestMe(p.p)) -- See! only coded once
-- Add any other necessary joins here
-- Select needs to deal with all the columns with identical names
SELECT d1.N AS AN, d1.V as AV,
d2.N AS BN, d2.V as BV,
d3.N AS CN, d3.V as CV
-- d1 gets limited to values where p = 2 in the where clause below
FROM AllData AS d1
-- Outer joins require the ANDs to restrict row multiplication
FULL JOIN AllData AS d2 ON d1.N = d2.N
AND d1.p = 2 AND d2.p = 4
FULL JOIN AllData AS d3 ON d1.N = d3.N
AND d1.p = 2 AND d2.p = 4 AND d3.p = 6
-- Since AllData actually contains all the rows we must limit the results
WHERE(d1.p = 2 OR d1.p IS NULL)
AND (d2.p = 4 OR d2.p IS NULL)
AND (d3.p = 6 OR d3.p IS NULL);
What you want to do is akin to a pivot and so the complexity of the needed query is similar to creating a pivot result without using the pivot statement.
Were you to use Pivot, duplicate rows (such as I included in this example) would be aggreagted. This is also a solution for doing a pivot where aggregation is unwanted.