SQL Join with a MIN condition
Hello,
I have two tables with the following data:
Table DESIGN
DOC_NO DOC_TITLE CLIENT_DOC_NO
240 MT/a Process Plant Site Grading General Plan 300-10C-011Table TRACK
FK_TRANS_NO FK_DOC_NO DUE_DATE FK_CLIENT_REV_NO
269 240 04/05/06 A
600 240 B
610 240 B
623 240 14/07/06 C
808 240 C
821 240 C
844 240 C
1036 240 0
1262 240 1
1341 240 1
1372 240 1
2567 240 2
2570 240 2
2576 240 2The required result is just the lower trans_no for each revision, somethig like this:
CLIENT_DOC_NO DOC_TITLE TRANS_NO REV DUE_DATE
300-10C-011 35 MT/a Process Plant Site Grading General Plan 269 A 04/05/06
300-10C-011 35 MT/a Process Plant Site Grading General Plan 600 B
300-10C-011 35 MT/a Process Plant Site Grading General Plan 623 C
300-10C-011 35 MT/a Process Plant Site Grading General Plan 1036 0 14/09/06
300-10C-011 35 MT/a Process Plant Site Grading General Plan 1262 1
300-10C-011 35 MT/a Process Plant Site Grading General Plan 2567 2So, I apply the MIN function to the TRACK.FK_TRANS_NO field and the result is:
CLIENT_DOC_NO DOC_TITLE TRANS_NO REV DUE_DATE
300-10C-011 35 MT/a Process Plant Site Grading General Plan 269 A 04/05/06
300-10C-011 35 MT/a Process Plant Site Grading General Plan 600 B
300-10C-011 35 MT/a Process Plant Site Grading General Plan 623 C
300-10C-011 35 MT/a Process Plant Site Grading General Plan 808 C 14/07/06 *************
300-10C-011 35 MT/a Process Plant Site Grading General Plan 1036 0 14/09/06
300-10C-011 35 MT/a Process Plant Site Grading General Plan 1262 1
300-10C-011 35 MT/a Process Plant Site Grading General Plan 2567 2 The ******* shows the row that I don't want but I can't remove from the result with any of the options tried right now, this has had me crazy for a couple days.
The SQL used right now is:
SELECT
DESIGN.CLIENT_DOC_NO,
DESIGN.DOC_TITLE,
TRACK.FK_TRANS_NO "TRANS_NO",
TRACK.FK_CLIENT_REV_NO "REV",
TRACK.DUE_DATE
FROM DESIGN, TRACK
WHERE (TRACK.FK_DOC_NO=DESIGN.DOC_NO)
AND (TRACK.TRANS_DATE IS NOT NULL)
GROUP BY
DESIGN.CLIENT_DOC_NO,
DESIGN.DOC_TITLE,
TRACK.FK_CLIENT_REV_NO,
TRACK.DUE_DATE
ORDER BY 4;Please if you can help to solve this, best regards.
Yup, thanks for the reminder on the keep keyword... I ended up with
CREATE TABLE design AS (
SELECT 240 doc_no, 'MT/a Process Plant Site Grading General Plan' doc_title, '300-10C-011' client_doc_no FROM DUAL
CREATE TABLE track AS (
SELECT 269 fk_trans_no, 240 fk_doc_no, TO_DATE('04/05/06', 'dd/mm/yy') due_date, 'A' fk_client_rev_no FROM DUAL UNION ALL
SELECT 600 fk_trans_no, 240 fk_doc_no, NULL due_date, 'B' fk_client_rev_no FROM DUAL UNION ALL
SELECT 610 fk_trans_no, 240 fk_doc_no, NULL due_date, 'B' fk_client_rev_no FROM DUAL UNION ALL
SELECT 623 fk_trans_no, 240 fk_doc_no, TO_DATE('14/07/06', 'dd/mm/yy') due_date, 'C' fk_client_rev_no FROM DUAL UNION ALL
SELECT 808 fk_trans_no, 240 fk_doc_no, NULL due_date, 'C' fk_client_rev_no FROM DUAL UNION ALL
SELECT 821 fk_trans_no, 240 fk_doc_no, NULL due_date, 'C' fk_client_rev_no FROM DUAL UNION ALL
SELECT 844 fk_trans_no, 240 fk_doc_no, NULL due_date, 'C' fk_client_rev_no FROM DUAL UNION ALL
SELECT 1036 fk_trans_no, 240 fk_doc_no, NULL due_date, '0' fk_client_rev_no FROM DUAL UNION ALL
SELECT 1262 fk_trans_no, 240 fk_doc_no, NULL due_date, '1' fk_client_rev_no FROM DUAL UNION ALL
SELECT 1341 fk_trans_no, 240 fk_doc_no, NULL due_date, '1' fk_client_rev_no FROM DUAL UNION ALL
SELECT 1372 fk_trans_no, 240 fk_doc_no, NULL due_date, '1' fk_client_rev_no FROM DUAL UNION ALL
SELECT 2567 fk_trans_no, 240 fk_doc_no, NULL due_date, '2' fk_client_rev_no FROM DUAL UNION ALL
SELECT 2570 fk_trans_no, 240 fk_doc_no, NULL due_date, '2' fk_client_rev_no FROM DUAL UNION ALL
SELECT 2576 fk_trans_no, 240 fk_doc_no, NULL due_date, '2' fk_client_rev_no FROM DUAL )
SELECT design.client_doc_no, design.doc_title, track.fk_trans_no "trans_no", track.fk_client_rev_no "rev", track.due_date
FROM design , (select track.* , rank() over (partition by fk_doc_no, fk_client_rev_no order by fk_trans_no) hmmm from track ) track
WHERE track.fk_doc_no = design.doc_no and hmmm = 1
ORDER BY 3;
CLIENT_DOC_ DOC_TITLE trans_no r DUE_DATE
300-10C-011 MT/a Process Plant Site Grading General Plan 269 A 04-MAI-06
300-10C-011 MT/a Process Plant Site Grading General Plan 600 B
300-10C-011 MT/a Process Plant Site Grading General Plan 623 C 14-JUL-06
300-10C-011 MT/a Process Plant Site Grading General Plan 1036 0
300-10C-011 MT/a Process Plant Site Grading General Plan 1262 1
300-10C-011 MT/a Process Plant Site Grading General Plan 2567 2
6 rows selected.
{code}which is of course not so cool ... :_|
edit: yeah I just cut the group by stuff away...
Edited by: Slow_moe on Jan 14, 2009 12:05 PM
Similar Messages
-
SQL JOIN with BPM sql component
Hello friends.
How to use SQL JOIN with BPM sql component?
The tables objects are created but the joined tables belong to different sql components .
I tried something like that, but a error "table doesn't exist" occours.
Ex:
for each element in
SELECT imuImovelCd
FROM IMOVEIS_URBANOS,
Integracao.FGLP.IMOVEIS_PRE_EDITAIS
WHERE IMOVEIS_URBANOS.imuImovelCd = Integracao.FGLP.IMOVEIS_PRE_EDITAIS.ipeImuCd
AND Integracao.FGLP.IMOVEIS_PRE_EDITAIS.ipePedNr = 1
AND Integracao.FGLP.IMOVEIS_PRE_EDITAIS.ipePedAa = 2008
do
extend this.imoveis using cdImovel = element.imuimovelcd,
nrImovel = call(DEC_ENDERECO, codimovel : element.imuimovelcd, tipoimovel : 1)
end
Edited by: user9008295 on 26/01/2010 05:19ok, ok you are right.
When I try use SQL Statement to make a JOIN with 2 tables on different sql objects, BPM returns "table dosn't exists".
So.... I change my code. I dont know if this is the best way to do, but... i hope u, or everyone, can help me to do a best work.
This code works fine.
for each element in
SELECT ipeImuCd
FROM Integracao.FGLP.IMOVEIS_PRE_EDITAIS
WHERE Integracao.FGLP.IMOVEIS_PRE_EDITAIS.ipePedNr = 1
AND Integracao.FGLP.IMOVEIS_PRE_EDITAIS.ipePedAa = 2008
do
for each element2 in
SELECT imuImovelDv
FROM IMOVEIS_URBANOS
WHERE imuImovelCd = element.ipeImuCd
do
extend this.imoveis using cdDvImovel = String(element2.imuImovelDv),
cdImovel = Decimal(element.ipeImuCd),
endereco = call(DEC_ENDERECO, codimovel : element.ipeImuCd, tipoimovel : 1)
end
end
Thx a lot!!! -
SQL Join with results in one line with multiple conditions
First post, new to the forum!
I have two tables which I am querying from, as an example
select a.f_name || a.l_name, case when b.bodypart='Arm' then ='Arm' end, case when b.bodypart='Leg' then 'Leg' end
from person a
join bodyparts b on b.person_id=a.person_id
where b.bodypart in ('Arm','Leg')
What this gives is something like:
BobNewhart Arm (null)
BobNewhart (null) Leg
I am trying to get the following results:
BobNewhard Arm Leg
This is just an example, but this should give a valid picture of the issue which i am having.
Thank you for any help!
RichieHi,
Like Whitehat said, use GROUP BY. You don't need a sub-query; just GROUP BY the name, and use MIN or MAX around the CASE expressions:
SELECT a.f_name || a.l_name
, MAX ( CASE
WHEN b.bodypart='Arm'
THEN ='Arm'
END
) AS arm
, MAX ( CASE
WHEN b.bodypart='Leg'
THEN ='Leg'
END
) AS leg
FROM person a
JOIN bodyparts b ON b.person_id = a.person_id
WHERE b.bodypart IN ('Arm','Leg')
GROUP BY a.f_name || a.l_name
;Since there will only be one value (at most) in the arm and leg columns, it doesn't matter if you use MIN or MAX. -
Data Foundation table joins with filters (multi-conditional joins)
My environment: Crystal Server 2011, Business View Manager 14.0.2.364, Crystal Reports 2011 with SP2 and FP28
In our existing database we make use of a single lookup table for many different types of selection lists.
For example, the lookup table might have selections for all of the US States (ex: NonUniqueIDValue = 123, Value1=TX, Value2=Texas, LookupType=US_STATES) and another list of selections for OrderStatus (ex: NonUniqueIDValue = 123, Value1=OPEN, Value2=NULL, LookupType=ORDER_STATUS).
It is necessary to supply addtional filtering on the join statement since the IDVaule for these entries are NOT unique.
Using SQL written joins for the two examples above would look like this:
join lookupTable on lookupTable.NonUniqueIDValue = mainTable.US_StateID AND lookupTable.LookupType = 'US_STATES'
join lookupTable on lookupTable.NonUniqueIDValue = mainTable.OrderStatus AND lookupTable.LookupType = 'ORDER_STATUS'
I am new to Business Views and don't readily see a solution since it appears the DF Linking window only suports single basic conditional testing (<, >, =, etc) . How can I accomplish this in my DF or elsewhere in the BV?
I would greatly appreciate any feedback or insight anyone might have on how to accomplish these kinds of filtered joins.
Thanks in advance...Hi Paul
If the query returns 100,000,000 rows, there will be performance issues of the report based on the connection and the datasource you are using.
If you use a Command Object or a Stored Procedure the query will be directly executed at the database level and the performance will not be affected much.
Hope this helps!
Thanks -
Outer Join with IN comparison condition
Dear all,
according to the manual:
"a WHERE condition cannot use the IN comparison condition to compare a column marked with the (+) operator with an expression"
Suppose I'm running a queries on hr sample schema:
SQL> select c.country_name,l.city from hr.countries c, hr.locations l where c.country_id=l.country_id (+) and l.city(+) in ('Roma','Tokyo');
COUNTRY_NAME CITY
Italy Roma
Japan Tokyo
Malaysia
Argentina
India
Israel
Nigeria
Netherlands
Egypt
Kuwait
Switzerland
COUNTRY_NAME CITY
France
United Kingdom
Belgium
Germany
Canada
United States of America
Mexico
Brazil
Zimbabwe
Singapore
COUNTRY_NAME CITY
Australia
Zambia
Denmark
China
26 rows selected.What didn't this fail?
Regards,
Val
Edited by: Valerie Debonair on Mar 4, 2011 4:39 AM
Edited by: Valerie Debonair on Mar 4, 2011 4:39 AMWorks on 11.2.0.1, although the documentation still says it shouldn't.
http://download.oracle.com/docs/cd/E11882_01/server.112/e17118/queries006.htm#SQLRF30046
SQL> select * from v$version;
BANNER
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
PL/SQL Release 11.2.0.1.0 - Production
CORE 11.2.0.1.0 Production
TNS for 32-bit Windows: Version 11.2.0.1.0 - Production
NLSRTL Version 11.2.0.1.0 - Production
SQL> select c.country_name,l.city
2 from hr.countries c, hr.locations l
3 where c.country_id=l.country_id (+) and l.city(+) in ('Roma','Tokyo');
COUNTRY_NAME CITY
Italy Roma
Japan Tokyo
Malaysia
Argentina
India
Israel
Nigeria
Netherlands
Egypt
Kuwait
Switzerland
COUNTRY_NAME CITY
France
United Kingdom
Belgium
Germany
Canada
United States of America
Mexico
Brazil
Zimbabwe
Singapore
Australia
COUNTRY_NAME CITY
Zambia
Denmark
China
25 ligne(s) sélectionnée(s). -
Single SQl Query with different where conditions
Experts,
I have a requirement to design a report. Here are the details
I have Report table layout
Profit center Gross sales (This Year) Gross Sales (Last Year) % change Year of Year
The Report has a selection of entering the Start Date.
I have a single table in oracle which has profit center and Gross Sales Values on daily basis.
I want to write a single sql query to calculate both Gross Sales current year and Gross Sales Last Year. I can calculate Gross Sales Current Year by putting the where condition for start date = Current Year Date which i pass through report. I want to calculate the Gross Sales Last Year in the Same query by putting the different where condition i.e start date = Last Year date based on the date input.
I dont know how to put two where conditions in single query for two different columns.
Any help will be appreciated.
Thanks in advance
Regards
Santoshinstead of changing your where clause couldn't you just determine the yearly totals from your table and then use the lag statement to get last years total?
something like this?
I just made up 10,000 days worth of sales and called it fake table it is supposed to represent a variant of the table you were describing as your base table.
with fake_table as
( select trunc(sysdate + level) the_day,
level daily_gross_sales
from dual
connect by level < 10001
select yr, year_gross_sale, lag(year_gross_sale) over (order by yr) prev_year_gross_sale,
(year_gross_sale - lag(year_gross_sale) over (order by yr))/year_gross_sale * 100 percent_change
from
(select distinct yr, year_gross_sale from
select the_day,
daily_gross_sales,
extract(year from the_day) yr,
extract(year from add_months(the_day,12)) next_yr,
sum(daily_gross_sales) over (partition by extract(year from the_day)) year_gross_sale
from fake_table
order by yr
) -
JPA Criteria : LEFT JOIN with an AND condition
Hi all,
I have a question regarding JPA criteria.
Here is my JPA query :
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Long> criteriaQuery = criteriaBuilder.createQuery(Long.class);
Root<Email> emailRoot = criteriaQuery.from(Email.class);
criteriaQuery.distinct(true);
Predicate globalCondition = criteriaBuilder.equal(emailRoot.get(Email_.type), EmailType.in);
Predicate responseMandatoryCondition = criteriaBuilder.equal(emailRoot.get(Email_.responseMandatory), true);
Predicate typeCondition = criteriaBuilder.notEqual(emailRoot.join(Email_.emailsOut, JoinType.LEFT).get(Email_.responseType),ResponseType.response);
globalCondition = criteriaBuilder.and(globalCondition, responseMandatoryCondition);
globalCondition = criteriaBuilder.and(globalCondition, typeCondition);
em.createQuery(mainCriteria.where(globalCondition)).getSingleResult();
Here is the result of this query :
SELECT DISTINCT email0_.ID AS col_0_0_
FROM EMAIL email0_
LEFT OUTER JOIN email emailso1_ ON email0_.ID = emailso1_.ID_EMAIL_IN
WHERE email0_.TYPE = 'in'
AND email0_.RESPONSE_MANDATORY = true
AND emailso1_.RESPONSE_TYPE <> 'response'
LIMIT 0 , 30
And here is the request I needed :
SELECT DISTINCT email0_.ID AS col_0_0_
FROM EMAIL email0_
LEFT OUTER JOIN email emailso1_ ON email0_.ID = emailso1_.ID_EMAIL_IN AND emailso1_.RESPONSE_TYPE <> 'response'
WHERE email0_.TYPE = 'in'
AND email0_.RESPONSE_MANDATORY = true
LIMIT 0 , 30
As you can see I need to check if the RESPONSE_TYPE is equals on the same line that the LEFT OUTER JOIN. Does anybody know how to write such an JPA criteria query ?
Thanks ,
Louis
Edited by: user13105928 on 17 févr. 2011 03:06You cannot define an ON clause with Criteria, nor JPQL.
Perhaps you can reword the query to avoid needing an ON clause.
What is the query you want to do (in english)?
Can you just use an OR in the where clause?
There is a enhancement request to have ON clause support added, please vote for it.
https://bugs.eclipse.org/bugs/show_bug.cgi?id=312146
James : http://www.eclipselink.org -
SQL query with lots of conditions issue..
Working on A large query that hits a large DB of parts.
The table I am given these parts are broken up into 4 fields.
Section,Groupid,Subgroupid,Component
When I hit this table, i am given a list of all the possible combo's of the 4 fields that can be used for that lookup at that time.
The problem is its SLOW when this list is pretty big.. a lot of times, over 200 rows of combos... so end up with something like below,
but stripped down for explaining...
So a generic version the query..
Select * from PartTable where
( (section='blah1') and (groupid='blah2') and (subgroupid='blah3') and (component='blah4') ) or
( (section='blah5') and (groupid='blah6') and (subgroupid='blah7') and (component='blah8') ) or
( (section='blah9') and (groupid='blah10') and (subgroupid='blah11') and (component='blah12') ) or
( (section='blah250') and (groupid='blah251') and (subgroupid='blah252') and (component='blah253') )I have changed it to a deal where I have a subquery and do a case statement to query a subquery, but the problem I run into that
is, is that 10g only allows so many. I can get around this by when i generate the query, to just make multiple case statements and then
modify my where statement.. but seems sloppy.. but "Works" .. using the OR statement deal, it can take near 30 seconds... with the
sloppy looking multiple case statement field deal, it takes 1.6 seconds..870023 wrote:
Try creating Index on these columns. Will help in CPU cost.That is one of the most useless pieces of advice I have ever seen.
CPU cost does not necessarily reflect performance. Creating too many indexes can also slow down performance. The first way of tackling a performance issue is to find out what the cause is, before trying to figure out the best way to fix it.
{message:id=9360003} -
Please look at this tables and help me how i do get result in "Result tbl" tables ..
try that !
select a.*, case
when a.item_type = 1 then b.inv_date
when a.item_type = 3 then c.deb_date
end as item_date
from receipt_item a
left join invoice b on a.item_id = b.invvi_id and a.item_type = 1
left join Debit c on a.item_id = c.deb_id and a.item_type = 3 -
Inner Join with Negative Condition
Hi Gurus,
I have to select data from two table and I have to exclude some records based on user selection
I am slecting data fromm MARC and MVKE and I have provided two select option for MTPOS from MVKE and EKGRP from MARC
Exclude the entries where both the field values match with an AND condition
i.e MVKEMTPOS = XXXX AND MARCEKGRP = YYYY
Can I write the below statement
Select . ....
JOIN ......
WHERE ( MVKE~MTPOS NOT IN S_MTPOS AND
MARC~EKGRP NOT IN S_EKGRP )A where clause on joined tables should work as a Open SQL does on a table read. In other words, if you have a select-options entry on the screen, and the user chose to OMIT a range (Exclude Between low high), I would expect to get the correct results with...
where..... IN selection-option range.
I would not, however, write a NOT IN select-option, though....the user would have already determined that with his Exclude choice, but it will be a lengthy data retrieval (full table scans).
On the other hand, if you expecting the user to say I-include between low and high as a range that is to be excluded then you can do your way, which should result in a full table scan on both tables, or you can retrieve the remainder of the where clause and the do a 2nd step to delete from your internal table where the values equal those to be omitted.
Is there any way you can convert this to include...such as looking up possible values, building a ranges table with Include where equal to a single value, then delete the entries that should be omitted from that ranges table....then it becomes
where field in my_ranges_table....a much faster retrieval. -
Performance tuning of sql query with multiple joins
My query takes at least half an hour to execute and the number of records returned are approx 1 lakh records.
Structure of tables are:
tblSession : ID,option1,option2,option3,option4,option5,option6,option7,option8,option9.
tblOption : ID, labelID
tblLabelDetail : ID, LABELID, text
optionID 1 to optionID9 are Foreign keys to table tblOption.ID
My query is as below :
select
session.ID
,session.tstamp
,session.score
,session.hid1
,session.hID2
,session.hID3
,session.collectionID
,session.consumerID
,session.langID
,cons_cust.text1 as customCons_text1,
cons_cust.text2 as customCons_text2,
cons_cust.text3 as customCons_text3,
cons_cust.text4 as customCons_text4,
cons_cust.text5 as customCons_text5,
cons_cust.text6 as customCons_text6,
cons_cust.text7 as customCons_text7,
cons_cust.text8 as customCons_text8,
cons_cust.text9 as customCons_text9,
ld_cons1.text as customCons_option1GUID,
ld_cons2.text as customCons_option2GUID,
ld_cons3.text as customCons_option3GUID,
ld_cons4.text as customCons_option4GUID ,
ld_cons5.text as customCons_option5GUID,
ld_cons6.text as customCons_option6GUID,
ld_cons7.text as customCons_option7GUID,
ld_cons8.text as customCons_option8GUID,
ld_cons9.text as customCons_option9GUID,
--session
session_cust.text1 as session_cust_text1,
session_cust.text2 as session_cust_text2,
session_cust.text3 as session_cust_text3,
session_cust.text4 as session_cust_text4,
session_cust.text5 as session_cust_text5,
session_cust.text6 as session_cust_text6,
session_cust.text7 as session_cust_text7,
session_cust.text8 as session_cust_text8,
session_cust.text9 as session_cust_text9,
ld_sess1.text as session_cust_option1GUID,
ld_sess2.text as session_cust_option2GUID,
ld_sess3.text as session_cust_option3GUID,
ld_sess4.text as session_cust_option4GUID,
ld_sess5.text as session_cust_option5GUID,
ld_sess6.text as session_cust_option6GUID,
ld_sess7.text as session_cust_option7GUID,
ld_sess8.text as session_cust_option8GUID,
ld_sess9.text as session_cust_option9GUID,
session_cust.tStamp1,
session_cust.tStamp2
from mvSession session with (noexpand)
inner join tblCollection c on c.ID=session.collectionID AND c.templateID = 405
left join tblConsumer cons on cons.ID=session.consumerID and cons.sessionYM between 601 and 1412 and cons.sID=105
left join vCustomConsumer cons_cust on cons_cust.sessionYM between 601 and 1412 and cons_cust.sID=105 and cons_cust.ID=cons.ID
left join tbloption o_cons1 on o_cons1.id = cons_cust.option1 and o_cons1.sid = 105
left join tblLabelDetail ld_cons1 on ld_cons1.labelID = o_cons1.labelID and ld_cons1.langId = 1 and ld_cons1.eid = 107
left join tbloption o_cons2 on o_cons2.id = cons_cust.option2 and o_cons2.sid = 105
left join tblLabelDetail ld_cons2 on ld_cons2.labelID = o_cons2.labelID and ld_cons2.langId = 1 and ld_cons2.eid = 107
left join tbloption o_cons3 on o_cons3.id = cons_cust.option3 and o_cons3.sid = 105
left join tblLabelDetail ld_cons3 on ld_cons3.labelID = o_cons1.labelID and ld_cons3.langId = 1 and ld_cons3.eid = 107
left join tbloption o_cons4 on o_cons4.id = cons_cust.option4 and o_cons4.sid = 105
left join tblLabelDetail ld_cons4 on ld_cons4.labelID = o_cons4.labelID and ld_cons4.langId = 1 and ld_cons4.eid = 107
left join tbloption o_cons5 on o_cons5.id = cons_cust.option5 and o_cons5.sid = 105
left join tblLabelDetail ld_cons5 on ld_cons5.labelID = o_cons5.labelID and ld_cons5.langId = 1 and ld_cons5.eid = 107
left join tbloption o_cons6 on o_cons6.id = cons_cust.option6 and o_cons6.sid = 105
left join tblLabelDetail ld_cons6 on ld_cons6.labelID = o_cons6.labelID and ld_cons6.langId = 1 and ld_cons6.eid = 107
left join tbloption o_cons7 on o_cons7.id = cons_cust.option7 and o_cons7.sid = 105
left join tblLabelDetail ld_cons7 on ld_cons7.labelID = o_cons7.labelID and ld_cons7.langId = 1 and ld_cons7.eid = 107
left join tbloption o_cons8 on o_cons8.id = cons_cust.option8 and o_cons8.sid = 105
left join tblLabelDetail ld_cons8 on ld_cons8.labelID = o_cons8.labelID and ld_cons8.langId = 1 and ld_cons8.eid = 107
left join tbloption o_cons9 on o_cons9.id = cons_cust.option9 and o_cons9.sid = 105
left join tblLabelDetail ld_cons9 on ld_cons9.labelID = o_cons9.labelID and ld_cons9.langId = 1 and ld_cons9.eid = 107
left join vCustomSession session_cust on session_cust.sessionYM between 601 and 1412 and session_cust.sID=105 and session_cust.ID=session.ID
left join tbloption o_sess1 on o_sess1.id = session_cust.option1 and o_sess1.sid = 105
left join tblLabelDetail ld_sess1 on ld_sess1.labelID = o_sess1.labelID and ld_sess1.langId = 1 and ld_sess1.eid = 107
left join tbloption o_sess2 on o_sess2.id = session_cust.option2 and o_sess2.sid = 105
left join tblLabelDetail ld_sess2 on ld_sess2.labelID = o_sess2.labelID and ld_sess2.langId = 1 and ld_sess2.eid = 107
left join tbloption o_sess3 on o_sess2.id = session_cust.option3 and o_sess3.sid = 105
left join tblLabelDetail ld_sess3 on ld_sess3.labelID = o_sess2.labelID and ld_sess3.langId = 1 and ld_sess3.eid = 107
left join tbloption o_sess4 on o_sess4.id = session_cust.option4 and o_sess4.sid = 105
left join tblLabelDetail ld_sess4 on ld_sess4.labelID = o_sess4.labelID and ld_sess4.langId = 1 and ld_sess4.eid = 107
left join tbloption o_sess5 on o_sess5.id = session_cust.option5 and o_sess5.sid = 105
left join tblLabelDetail ld_sess5 on ld_sess5.labelID = o_sess5.labelID and ld_sess5.langId = 1 and ld_sess5.eid = 107
left join tbloption o_sess6 on o_sess6.id = session_cust.option6 and o_sess6.sid = 105
left join tblLabelDetail ld_sess6 on ld_sess6.labelID = o_sess6.labelID and ld_sess6.langId = 1 and ld_sess6.eid = 107
left join tbloption o_sess7 on o_sess7.id = session_cust.option7 and o_sess7.sid = 105
left join tblLabelDetail ld_sess7 on ld_sess7.labelID = o_sess7.labelID and ld_sess7.langId = 1 and ld_sess7.eid = 107
left join tbloption o_sess8 on o_sess8.id = session_cust.option8 and o_sess8.sid = 105
left join tblLabelDetail ld_sess8 on ld_sess8.labelID = o_sess8.labelID and ld_sess8.langId = 1 and ld_sess8.eid = 107
left join tbloption o_sess9 on o_sess9.id = session_cust.option9 and o_sess9.sid = 105
left join tblLabelDetail ld_sess9 on ld_sess9.labelID = o_sess9.labelID and ld_sess9.langId = 1 and ld_sess9.eid = 107
where session.sID=105 and session.tStamp >= 'Sep 1 2014 12:00AM' and session.tStamp < 'Dec 12 2014 12:00AM'
order by session.tStamp, session.ID
Is there a way , where i can simplify the joins with tbloption and tblLabelDetail and get my o/p in optimal time.
RegardsI have headed towards another approach ie. using unpivot and then pivot.
First i am converting option1-option9 into column , then doing PIVOT to get back the same record . But issue is that when i am doing pivoting i am getting NULL values.
My query is :
select * into #t1 from
select ID
, option1
, option2
, option3
, option4
, option5
, option6
, option7
, option8
, option9
from vCustomConsumer
where sid=105
and sessionYM = 1412
) SourceTable
UNPIVOT
optionID FOR Col IN
(option1
,option2
,option3
,option4
,option5
,option6
,option7
,option8
,option9 )
) AS unpvt
select t.ID,t.optionID,t.col,cast(ld.text as varchar(max)) as text into #t2
from #t1 t
left outer join tbloption o on o.ID = t.optionID
left outer join tblLabelDetail ld on ld.labelID = o.labelID and ld.langID=1
order by ID,col
select ID,option1
,option2
,[option3]
,option4
,option5
,option6
,option7
,option8
,option9
from
select ID,optionID,col,text
from #t2
)up
pivot
min(text)for col in
(option1
,option2
,[option3]
,option4
,option5
,option6
,option7
,option8
,option9
)as pvt
In my last query where i am using pivot, i am getting NULL values. When i check the data in temp table #t2 , it exists perfectly . But when pivoting i dont understand why it is returning most of the NULL values. I am getting data for only one column in single
row.
Below are some rows from result set finally obtained after pivoting :
ID
option1
option2
option3
option4
option5
option6
option7
option8
option9
62949026
NULL
0 to 200 seconds
NULL
NULL
NULL
NULL
NULL
NULL
NULL
62966000
NULL
NULL
4
NULL
NULL
NULL
NULL
NULL
NULL
62966032
NULL
NULL
4
NULL
NULL
NULL
NULL
NULL
NULL
63090372
NULL
NULL
NULL
NULL
EN
NULL
NULL
NULL
NULL
63090375
NULL
NULL
NULL
NULL
EN
NULL
NULL
NULL
NULL
Thanks, -
Oracle 8i, left join with conditional
Coming from the MySQL world, I'm trying to do a left join with a
condition:
select c.givenname,c.surname,c.userid,r.letternr
from cand c,responses r
where (c.userid=r.username(+))
and
c.activeprofile=1
No problem whatsoever.
If there is no corresponding "response" in R for a given
candidate, I get a NULL return for R.letternr.
However, there is a flag in R, called "VISIBLE" that I wish to
use to mean "Don't count this entry in R". R.VISIBLE=0 means
that the response is not active/present/visible/valid.
Am I making any sense? :-)If you don't want to display a row with a null value for
r.letternr when r.visible = 0, then:
SELECT c.givenname,
c.surname,
c.userid,
r.letternr
FROM cand c,
responses r
WHERE c.userid = r.username (+)
AND c.activeprofile = 1
AND r.visible != 0
Or, if you do want to display a row with a null value for
r.letternr when r.visible = 0, then:
SELECT c.givenname,
c.surname,
c.userid,
r.letternr
FROM cand c,
responses r
WHERE c.userid = r.username (+)
AND c.activeprofile = 1
AND r.visible (+) != 0 -
SQL Server Multiple JOINS with Table Value Function - query never ends
I have a query with 4 joins using a table value function to get the data and when I execute it the query never ends.
Issue Details
- Table value function
CREATE FUNCTION [dbo].[GetIndicator]
@indicator varchar(50),
@refDate datetime
RETURNS
TABLE
AS
RETURN
SELECT
T1.Id ,T1.ColINT_1, T1.ColNVARCHAR_1 collate DATABASE_DEFAULT as ColNVARCHAR_1 ,T1.ColNVARCHAR_2 ,T1.ColSMALLDATETIME_1, T1.ColDECIMAL_1, T1.ColDECIMAL_1
FROM TABLE2 T2
JOIN TABLE3 T3
ON T2.COLFKT3 = T3.Id
AND T3.ReferenceDate = @RefDate
AND T3.State != 'Deleted'
JOIN TABLE4 T4
ON T2.COLFKT4 = T4.Id AND T4.Name=@indicator
JOIN TABLE1 T1
ON T2.COLFKT1=T1.Id
- Query
DECLARE @RefDate datetime
SET @RefDate = '30 April 2014 23:59:59'
SELECT DISTINCT OTHERTABLE.Id As Id
FROM
GetIndicator('ID#1_0#INDICATOR_X',@RefDate) AS OTHERTABLE
JOIN GetIndicator('ID#1_0#INDICATOR_Y',@RefDate) AS YTABLE
ON OTHERTABLE.SomeId=YTABLE.SomeId
AND OTHERTABLE.DateOfEntry=YTABLE.DateOfEntry
JOIN GetIndicator('ID#1_0#INDICATOR_Z',@RefDate) AS ZTABLE
ON OTHERTABLE.SomeId=ZTABLE.SomeId
AND OTHERTABLE.DateOfEntry=ZTABLE.DateOfEntry
JOIN GetIndicator('ID#1_0#INDICATOR_W',@RefDate) AS WTABLE
ON OTHERTABLE.SomeId=WTABLE.SomeId
AND OTHERTABLE.DateOfEntry=WTABLE.DateOfEntry
JOIN GetIndicator('ID#1_0#INDICATOR_A',@RefDate) AS ATABLE
ON OTHERTABLE.SomeId=ATABLE.SomeId
AND OTHERTABLE.DateOfEntry=ATABLE.DateOfEntry
Other details:
- SQL server version: 2008 R2
- If I execute the table function code outside the query, with the same args, the execution time is less the 1s.
- Each table function call return between 250 and 500 rows.Hi,
Calling function in general is a costly query. And definitely joining with a function 5 times in not an efficient one.
1. You can populate the results for all parameters in a CTE or table variable or temporary table and join (instead of funtion) for different parameters
2. Looks like you want fetch the IDs falling to different indicators for the same @Refdate. You can try something like this
WITH CTE
AS
SELECT
T1.Id ,T1.ColINT_1, T1.ColNVARCHAR_1 collate DATABASE_DEFAULT as ColNVARCHAR_1 ,T1.ColNVARCHAR_2 ,T1.ColSMALLDATETIME_1, T1.ColDECIMAL_1, T1.ColDECIMAL_1, T4.Name
FROM TABLE2 T2
JOIN TABLE3 T3
ON T2.COLFKT3 = T3.Id
AND T3.ReferenceDate = @RefDate
AND T3.State != 'Deleted'
JOIN TABLE4 T4
ON T2.COLFKT4 = T4.Id AND T4.Name=@indicator
JOIN TABLE1 T1
ON T2.COLFKT1=T1.Id
SELECT * FROM CTE WHERE Name = 'ID#1_0#INDICATOR_X' AND Name = 'ID#1_0#INDICATOR_Y' AND Name = 'ID#1_0#INDICATOR_Z' AND Name = 'ID#1_0#INDICATOR_W' AND Name = 'ID#1_0#INDICATOR_A' AND ReferenceDate = @RefDate.
Or you can even simplify more depends on your requirement.
Regards,
Brindha. -
T-sql 2008 r2 cte join with a second table
In a sql server 2008 r2 database, I am trying to take the results of the cte called sProgram and join the results with the Person table in the query. The syntax of the join looks ok, however the results of the join are incorrect. The joined results are null
when there is really data that can be joined. Can you tell me how to join the query so the results of the sprogram cte will be joined to the Person table correctly?
1. Here is the query:
;with sProgram as (
SELECT [personID],[attributeID],[value], [date],ROW_NUMBER() OVER(Partition by[personID] ORDER BY [personID],[date] DESC) rn
FROM [dbo].[CustomS]
where [attributeID] in ('562','563','564','565')
,programSelect as
select [personID],[attributeID],[value],[date]
from sProgram
where rn=1
SELECT person.personID
, cs562.personID
, cs562.attributeID
, cs562.value
, cs562.[date]
, cs563.personID
, cs563.attributeID
, cs563.value
, cs563.[date]
, cs564.personID
, cs564.attributeID
, cs564.value
, cs564.[date]
, cs565.personID
, cs565.attributeID
, cs565.value
, cs565.[date]
FROM Person cs562
join programSelect on cs562.personID = Person.personID and cs562.attributeID= '562'
left join programSelect cs563 on cs563.personID = cs562.personID and cs563.[Date] = cs562.[date] and cs563.attributeID ='563'
left join programSelect cs564 on cs564.personID = cs563.personID and cs564.[date] = cs563.[Date] and cs564.attributeID ='564'
left join programSelect cs565 on cs565.personID = cs564.personID and cs565.[Date] = cs564.[date] and cs565.attributeID ='565'
GROUP BY
person.personID
, cs562.personID
, cs562.attributeID
, cs562.value
, cs562.[date]
, cs563.personID
, cs563.attributeID
, cs563.value
, cs563.[date]
, cs564.personID
, cs564.attributeID
, cs564.value
, cs564.[date]
, cs565.personID
, cs565.attributeID
, cs565.value
, cs565.[date]
2. here is the CustomS table with some data.
SELECT [CustomSID]
,[personID]
,[attributeID]
,[value]
,[date]
FROM [dbo].[CustomS]
where personID=7170
and attributeID in (562,563,564,565)
order by date desc
CustomSID personID attributeID value [date]
262490684 7170 562 GA 2013-08-14 07:26:00
262490683 7170 565 05/23/2014 2013-08-14 07:26:00
262490682 7170 563 Acd 2013-08-14 07:26:00
262490681 7170 564 08/14/2013 2013-08-14 07:26:00
251784 7170 564 09/06/2007 2007-09-08 00:00:00
250029 7170 562 MA 2007-09-08 00:00:00
248287 7170 563 asp 2007-09-08 00:00:00
251785 7170 564 09/07/2006 2006-09-08 00:00:00
248286 7170 563 asp 2006-09-08 00:00:00
250028 7170 562 MA 2006-09-08 00:00:00
251783 7170 564 09/06/2006 2006-09-06 00:00:00
249367 7170 562 LA 2006-09-06 00:00:00
248285 7170 563 asp 2006-09-06 00:00:00
3. Here is the table definition:
here is the table definition:
alter TABLE [dbo].[CustomS](
[CustomSID] [int] IDENTITY(1,1) NOT NULL,
[personID] [int] NOT NULL,
[attributeID] [int] NOT NULL,
[value] [varchar](256) NULL,
[date] [smalldatetime] NULL,Partition by CustomsID will didvide data into groups based on CustomsID value.
ROW_NUMBER will generate sequence numbers over the group and when you look for rn=1 you'll get record with latest group
Also from what I understand you need just this instead of all those left joins
;with sProgram as (
SELECT [personID],[attributeID],[value], [date],
ROW_NUMBER() OVER(Partition by [personID],[attributeID] ORDER BY [date] DESC) rn
FROM [dbo].[CustomS]
where [attributeID] in ('562','563','564','565')
SELECT p.personID
, pr.personID , pr.attributeID , pr.value , pr.[date]
, pr1.*
FROM Person p
left join sProgram pr
on pr.personID = p.personID
and pr.Rn = 1
and attributeID = '562'
outer apply (SELECT personID,
max(case when attributeID = '563' then attributeID end) as AttrID563,
max(case when attributeID = '563' then value end) as Value563,
max(case when attributeID = '563' then date end) as date563,
max(case when attributeID = '564' then attributeID end) as AttrID564,
max(case when attributeID = '564' then value end) as Value564,
max(case when attributeID = '564' then date end) as date564,
max(case when attributeID = '565' then attributeID end) as AttrID565,
max(case when attributeID = '565' then value end) as Value565,
max(case when attributeID = '565' then date end) as date565
where personID = p.PersonID
and [date] = pr.[date]
and Rn = 1
group by personId)pr1
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
Why has my ipad mini stopped connecting with my iPhone 4S? I used to use it to download books, or transfer emails to my ipad mini. It was fine 3 days ago, now I get a message saying " cannot join with iPhone" Any help greatly appreciated.
You can try resetting your iPad and iPhone by simultaneously pressing and holding the Home and Sleep/Wake buttons until you see the Apple Logo. This can take up to 15 seconds so be patient and don't release the buttons until the logo appears.
Try again to see if the problem persists.
Maybe you are looking for
-
How do i get my imac to remember my login details on my email and Facebook without remembering my passwords?? iAt the moment i have to type each time i visit my sites??
-
Benefits: Health plans show costs with bi-weekly rates in Enrollment screen
Hello, I have created 2 new health plans. During testing, I noticed when trying to enroll employees via the Enrollment screen, the plan options show costs with bi-weekly rates rather than monthly rates. For these health plans, I had set the cost va
-
ATI 5750 and Photoshop CC ISSUE
I'm having driver issues with the ATI Radeon HD 5750 and Photoshop CC. You can see from the screenshot the lines going through the image I have contacted Adobe they are aware of the problem. Its in your hands now Apple to resolve
-
When you download themes or extensies it says add to Firefox or its not available for Firefox 3.5.5. Now the strange thing is that when i want to install the add-ons/themes i downloaded it gives the message doesnt supp Firefox 9.0.1 but when i try to
-
How many work processes are recommended by SAP for 16 GB RAM
How many work processes are recommended by SAP for 16 GB RAM ?