How to Merge SQL Query(Help required) - sql-server

Dear friends, below are my two SQL queries:
select distinct
a_bm.DestProvider_ID,
a_bm.DestCircel_ID,
convert(datetime,dbo.fnToDate(a_bm.BM_BillFrom),103) as fromdate,
convert(datetime,dbo.fnToDate(a_bm.BM_BillTo),103) as todate,
t_rec.TapInRec as BillRecevable,
t_rec.TapInRec as Billreceied
from Auditdata_BillingMaster a_bm
inner join TapInRecordMaster t_rec
on a_bm.DestProvider_ID = t_rec.DestProviderMaster_ID
and a_bm.DestCircel_ID = t_rec.DestCircelMaster_ID
and convert(datetime,dbo.fnToDate(a_bm.BM_BillFrom),103)> =
convert(datetime,t_rec.Months)
and convert(datetime,dbo.fnToDate(a_bm.BM_BillTo),103)<=
convert(datetime,t_rec.BillTo)
where a_bm.DestProvider_ID=4
and a_bm.DestCircel_ID=22
and a_bm.typeoffile=1
and convert(datetime,dbo.fnToDate(a_bm.BM_BillFrom),103)>=
convert(datetime,'6/1/2009')
and convert(datetime,dbo.fnToDate(a_bm.BM_BillFrom),103)<=
convert(datetime,'7/30/2009')
select Temp_tbl.fromdate from Temp_tbl Temp_tbl
inner join (
select
convert(datetime,dbo.fnToDate(BM_BillFrom),103) as a1,
convert(datetime,dbo.fnToDate(BM_BillTo),103) as b1,
count(*) as c1,
am_bm.DestProvider_ID,
am_bm.DestCircel_ID
from Auditdata_BillingMaster am_bm
inner join Temp_tbl tmp
on tmp.Provider_ID=am_bm.DestProvider_ID
and tmp.Circel_ID=am_bm.DestCircel_ID
where convert(datetime,tmp.fromdate)>=
convert(datetime,dbo.fnToDate(am_bm.BM_BillFrom),103)
and convert(datetime,tmp.todate) <=
convert(datetime,dbo.fnToDate(am_bm.BM_BillTo),103)
group by
convert(datetime,dbo.fnToDate(BM_BillFrom),103),
convert(datetime,dbo.fnToDate(BM_BillTo),103),
am_bm.DestProvider_ID,
am_bm.DestCircel_ID
) b
on Temp_tbl.Provider_ID = b.DestProvider_ID
and Temp_tbl.Circel_ID = b.DestCircel_ID
and convert(datetime,Temp_tbl.fromdate,101)>= convert(datetime,(b.a1),101)
and convert(datetime,Temp_tbl.todate) <= convert(datetime,(b.b1),101)
I want to merge above 2 SQL query in SQL Server 2000.
Please help me.
Thanks in advance.

Do you mean to JOIN or UNION both tables?
If you mean to JOIN both query results, simply take both results as input for JOIN statement.
How you join both results is really dependent on your database design. Preferably the join is based on referential integrity enforcing the relationship between the results to ensure data integrity. But since you do not mention the join condition, let me assume you will join based on DestProvider_ID & DestCircel_ID.
select
result1.DestProvider_ID,
result1.DestCircel_ID,
result1.fromdate,
result1.todate,
result1.BillRecevable,
result1.Billreceied,
result2.fromdate
from
( *your first query* ) as result1
inner join
(select
Temp_tbl.fromdate,
am_bm.DestProvider_ID,
am_bm.DestCircel_ID
from Temp_tbl Temp_tbl
*the rest of your second query*
) as result2 on result1.DestProvider_ID = result2.DestProvider_ID
and result1.DestCircel_ID = result2.DestCircel_ID
UNION:
If you want to take multiple select statements and combine them into one result set, UNION statement is the easiest way to go:
SELECT column1a, column2a, column3a FROM tableA
UNION
SELECT column1b, column2b, column3b FROM tableB
This is possible only if:
both queries have same number of columns
Corresponding columns in each query expression must be of the same data type
data type of column1a == column1b
data type of column2a == column2b
data type of column3a == column3b
Since both of your queries do not have same number of columns, you can't merge them, at least with UNION select.

Related

RIGHT\LEFT Join does not provide null values without condition

I have two tables one is the lookup table and the other is the data table. The lookup table has columns named cycleid, cycle. The data table has SID, cycleid, cycle. Below is the structure of the tables.
If you check the data table, the SID may have all the cycles and may not have all the cycles. I want to output the SID completed as well as missed cycles.
I right joined the lookup table and retrieved the missing as well as completed cycles. Below is the query I used.
SELECT TOP 1000 [SID]
,s4.[CYCLE]
,s4.[CYCLEID]
FROM [dbo].[data] s3 RIGHT JOIN
[dbo].[lookup_data] s4 ON s3.CYCLEID = s4.CYCLEID
The query is not displaying me the missed values when I query for all the SID's. When I specifically query for a SID with the below query i am getting the correct result including the missed ones.
SELECT TOP 1000 [SID]
,s4.[CYCLE]
,s4.[CYCLEID]
FROM [dbo].[data] s3 RIGHT JOIN [dbo].[lookup_data] s4
ON s3.CYCLEID = s4.CYCLEID
AND s3.SID = 101002
ORDER BY [SID], s4.[CYCLEID]
As I am supplying this query into tableau I cannot provide the sid value in the query. I want to return all the sid's and from tableau I will be do the rest of the things.
The expected output that i need is as shown below.
I wrote a cross join query like below to acheive my expected output
SELECT DISTINCT
tab.CYCLEID
,tab.SID
,d.CYCLE
FROM ( SELECT d.SID
,d.[CYCLE]
,e.CYCLEID
FROM ( SELECT e.sid
,e.CYCLE
FROM [db_temp].[dbo].[Sheet3$] e
) d
CROSS JOIN [db_temp].[dbo].[Sheet4$] e
) tab
LEFT OUTER JOIN [db_temp].[dbo].[Sheet3$] d
ON d.CYCLEID = tab.CYCLEID
AND d.SID = tab.SID
ORDER BY tab.SID
,tab.CYCLEID;
However I am not able to use this query for more scenarios as my data set have nearly 20 to 40 columns and i am having issues when i use the above one.
Is there any way to do this in a simpler manner with only left or right join itself? I want the query to return all the missing values and the completed values for the all the SID's instead of supplying a single sid in the query.
You can create a master table first (combine all SID and CYCLE ID), then right join with the data table
;with ctxMaster as (
select distinct d.SID, l.CYCLE, l.CYCLEID
from lookup_data l
cross join data d
)
select d.SID, m.CYCLE, m.CYCLEID
from ctxMaster m
left join data d on m.SID = d.SID and m.CYCLEID = d.CYCLEID
order by m.SID, m.CYCLEID
Fiddle
Or if you don't want to use common table expression, subquery version:
select d.SID, m.CYCLE, m.CYCLEID
from (select distinct d.SID, l.CYCLE, l.CYCLEID
from lookup_data l
cross join data d) m
left join data d on m.SID = d.SID and m.CYCLEID = d.CYCLEID
order by m.SID, m.CYCLEID

Compare a "temp' table with values in CTE, then update two different tables

I have a "temp' table populated from an enrollment transportable in java. What I am doing is comparing the "temp" table with values I am populating in a CTE with a select query. What I need to do next is update two different tables. Here is my query for the comparison of the "temp" table and CTE:
WITH CTE AS
(
SELECT S.SYS_USER_NAME, PG.PAX_ID
FROM component.SYS_USER S
INNER JOIN component.PAX_GROUP PG
ON S.PAX_ID = PG.PAX_ID
WHERE (ROLE_CODE = 'AC' and THRU_DATE is null) or
(ROLE_CODE = 'DLRP' and THRU_DATE is null)
)
SELECT * FROM CTE
INNER JOIN component.TEMP_CONTROL_NUM
ON TEMP_CONTROL_NUM.CONTROL_NUM = CTE.SYS_USER_NAME
What I want to do next is update two different tables. One I need to set a status column as inactive and the other I need to set a thru date.
The issue I am having is writing an UPDATE with a SELECT. I have something like:
UPDATE component.SYS_USER SET STATUS = 'I'
WHERE SYS_USER_NAME =
(SELECT * FROM CTE INNER JOIN component.TEMP_CONTROL_NUM ON
TEMP_CONTROL_NUM = CTE.SYS_USER_NAME)
Would this be correct? I realize I am only attempting to update one table but I figure if I have one table updating, I can figure out the other. It doesn't seem to be.
Thank you in advance.
;WITH CTE as
(
...
)
UPDATE u SET
STATUS = 'I'
FROM component.SYS_USER u
INNER JOIN CTE c on c.SYS_USER_NAME = u.SYS_USER_NAME
INNER JOIN component.TEMP_CONTROL_NUM t ON t.TEMP_CONTROL_NUM = c.SYS_USER_NAME

Update using three tables in netezza

I am trying to avoid a co-related sub query which in turn made me to update from three different tables and I am not quite sure how to do updates from three tables using netezza.
update stemp
set maxi = a.marks
from stemp
left join
sd696 sd
where st.id = sd.id
left join
(select id,MAX(marks) marks from sm696 group by ID) a
where a.id = sd.id;
Please help me
When you require joins in UPDATEs, the joins are specified implicitly in a comma separated FROM clause (without specifying the UPDATEd table again), with the JOIN criteria being specified in the WHERE clause.
Your UPDATE would look something like this:
UPDATE stemp
SET maxi = a.marks
FROM sd696 sd,
(
SELECT id,
MAX(marks) marks
FROM sm696
GROUP BY ID
)
a
WHERE stemp.id = sd.id
AND a.id = sd.id;

Union of Joins vs. Join of unions

I'm trying to choose between what I think are two choices to get the same data.
I have one table that has the IDs of interest, and a set of 4 tables similar to each other that have data for those IDs. Once I have the rows for each ID, I'll use them to get maximum status field, or the minimum date field, etc. (across the 4 tables).
I can see structuring this query as 1 join to a union of the 4 tables, or as a union of 4 joins. Which is more efficient? FWIW, I find the first easier to understand, and probably easier to maintain.
Spelling out the two choices:
Join idTable against a sub-select of the 4 tables UNIONed together:
select ss.id, ss.study, ss.status, ss.date
from ( -- subselect ss
select tx.id, tx.study, tx.status, tx.date
from table_tx tx
UNION
select cfu.id, cfu.study, cfu.status, cfu.date
from table_cfu cfu
UNION
select sfu.id, sfu.study, sfu.status, sfu.date
from table_sfu sfu
UNION
select bsl.id, bsl.study, bsl.status, bsl.date
from table_bsl bsl
) ss
inner join
idTable id on id.id = ss.id AND id.study = ss.study
A union of idTable joined against each of the four:
select tx.id, tx.study, tx.status, tx.date
from table_tx tx
inner join
idTable id on id.id = tx.id AND id.study = tx.study
UNION
select cfu.id, cfu.study, cfu.status, cfu.date
from table_cfu cfu
inner join
idTable id on id.id = cfu.id AND id.study = cfu.study
UNION
select sfu.id, sfu.study, sfu.status, sfu.date
from table_sfu sfu
inner join
idTable id on id.id = sfu.id AND id.study = sfu.study
UNION
select bsl.id, bsl.study, bsl.status, bsl.date
from table_bsl bsl
inner join
idTable id on id.id = bsl.id AND id.study = bsl.study
Or is there a better choice other than these?
It's going to depend on what your data looks like in terms of the number of rows in each of the tables, so your best bet is going to be trying out both approaches and seeing if either is better.
If I assume, though, that each of your tables tx, cfu, sfu, and bsl contain a million rows, then I expect it would be faster to limit those 4 large sets to a single row before unioning them as opposed to creating a 4-million row set and then joining it.
SQL Server can transform the first to the second but not the reverse.
That said, there is no way to know which is better because it depends on a lot of things (row counts, filter selectivity, ...). The only sound answer is to look at the plan and/or test.

Query Executing Problem

Using SQL 2005: “Taking too much time to execute”
I want to filter the date, the date should not display in holidays, and I am using three tables with Inner Join
When I run the below query, It taking too much time to execute, because I filter the cardeventdate with three table.
Query
SELECT
PERSONID, CardEventDate tmp_cardevent3
WHERE (CardEventDate NOT IN
(SELECT T_CARDEVENT.CARDEVENTDATE
FROM T_PERSON
INNER JOIN T_CARDEVENT ON T_PERSON.PERSONID = T_CARDEVENT.PERSONID
INNER JOIN DUAL_PRO_II_TAS.dbo.T_WORKINOUTTIME ON T_CARDEVENT.CARDEVENTDAY = DUAL_PRO_II_TAS.dbo.T_WORKINOUTTIME.DAYCODE
AND T_PERSON.TACODE = DUAL_PRO_II_TAS.dbo.T_WORKINOUTTIME.TACODE
WHERE (DUAL_PRO_II_TAS.dbo.T_WORKINOUTTIME.HOLIDAY = 'true')
)
)
ORDER BY PERSONID, CardEventDate DESC
For the above mentioned Query, there is any other way to do date filter.
Expecting alternative queries for my query?
I'm pretty sure that it's not the joined tables that is the problem, but rather the "not in" that makes it slow.
Try to use a join instead:
select m.PERSONID, m.CardEventDate
from T_PERSON p
inner join T_CARDEVENT c on p.PERSONID = c.PERSONID
inner join DUAL_PRO_II_TAS.dbo.T_WORKINOUTTIME w
on c.CARDEVENTDAY = w.DAYCODE
and p.TACODE = w.TACODE
and w.HOLIDAY = 'true'
right join tmp_cardevent3 m on m.CardEventDate = c.CardEventDate
where c.CardEventDate is null
order by m.PERSONID, m.CardEventDate desc
(There is a from clause missing from your query, so I don't know what table you are trying to get the data from.)
Edit:
Put tmp_cardevent3 in the correct place.
Have you created indices on all of the columns that you are using to do the joins? In particular, I'd consider indices on PERSONID in T_CARDEVENT, TACODE in both T_PERSON and T_WORKINOUTTIME, and HOLIDAY in T_WORKINOUTTIME.

Resources