Connect by sub query
Hi All,
I have a query..I have a table employee ..I also have an another table manager
I have two tables. employee and manager tables.
employee columns: emp_key, emp_name,parent_emp_id , level_no
manager columns: man_key,man_name,man_id
I should check the manager key equals emp key . if found i shud check whether emp key has parent emp key, if found i shud take emp name of that row and update in manager name in manager table.
I tried co related sub query but it works only in select statement but not update. can any one help me on this .Also can any one tell me whether we can use CONNECT BY PRIOR statement. any one tell me whether we can use CONNECT BY PRIOR statement.
Hi,
Sorry, I still don't uderstand the problem well enough to help.
The INSERT statements look okay now. What did you do to make them appear? (It would be good to know, when other people have the same problem.)
Can you do something similar to make the CREATE TABLE statements appear?
You have 4 rows in one table and 1 row in another table. You want to write an UPDATE statement (or something) that changes them. Is that right?
What should be in the changed tble after that UPDATE statement? Use a text editor to show what "SELECT * FROM ..." should produce. Post it on this site, but type these 6 characters:
\(small letters only, inside curly brackets) before and after each the section of formatted text, to preserve spacing.
MERGE is often eaiser than UPDATE, especially if the UPDATE statement would need a complicated WHERE clause.
It might help to see the UPDATE statement you tried, even though it doesn't work.
Similar Messages
-
Can someone please help me with a sub query question?
I need to list a 3rd party contract and then a list of students who belong to that contract.
On the students segment of the listing I need to show students with student id, name, total credit hours,
total amount spent on tuition, total amount spent on books and total amount spent on misc.
This code has a query for the contract information and I get that just fine.
Then it has a query that gives me total credit hours and that works fine
then it has a query that gives me total amount spent on tuition and that works fine
but
when I add the next query to get total amount spent on books I get only the information for the contract, I don't get student stuff anymore.
I would really appreciate any guidance that you could give.
Thanks in advance, Bob Hohulski
DECLARE
l_conn utl_TCP.connection;
v_filehandle utl_file.file_type;
v_output varchar2(1000);
v_contract_id varchar2(9);
v_contract_addr1 varchar2(30);
v_contract_addr2 varchar2(30);
v_contract_city varchar2(20);
v_contract_stat varchar2(03);
v_contract_zip varchar2(10);
v_contract_name varchar2(60);
v_student_id varchar2(09);
v_student_first_name varchar2(15);
v_student_mid_name varchar2(15);
v_student_last_name varchar2(60);
v_last_out varchar2(20);
v_student_detail_code varchar2(04);
v_student_amount number(12,2);
v_student_ref_number varchar2(09);
v_credit_hrs number(7,2);
v_tuition_amount number(12,2);
v_books_amount number(12,2);
v_misc_amount number(12,2);
v_total_for_student number(12,2);
v_current_student varchar2(09);
v_sftregs_pidm varchar2(09);
v_tbraccd_pidm varchar2(09);
CURSOR c_sel_contract IS
SELECT DISTINCT spriden_id, spriden_last_name,
spraddr_street_line1, spraddr_street_line2,
spraddr_city, spraddr_stat_code, spraddr_zip
FROM spriden, spraddr
-- WHERE spriden_id = '&Enter_Id'
where spriden_id = 'T10474666'
AND spriden_pidm = spraddr_pidm
AND SPRIDEN_CHANGE_IND IS NULL;
CURSOR c_sel_student IS
SELECT DISTINCT spriden_id, spriden_first_name, spriden_mi, spriden_last_name,
sftregs_credit_hr,
tbraccd_amount,
sftregs_pidm,
tbraccd_pidm
FROM spriden, tbraccd, tbbcstu, sftregs
WHERE 559220 = tbbcstu_contract_pidm
AND spriden_pidm = tbraccd_pidm
AND spriden_pidm = tbbcstu_stu_pidm
AND spriden_pidm = sftregs_pidm
AND (sftregs_pidm, sftregs_credit_hr) IN
(SELECT DISTINCT sftregs_pidm, SUM(sftregs_credit_hr)
FROM sftregs, tbbcstu, spriden
WHERE sftregs_term_code = '201010'
AND sftregs_pidm = tbbcstu_stu_pidm
AND sftregs_pidm = spriden_pidm
GROUP BY sftregs_pidm)
AND (tbraccd_pidm, tbraccd_amount) IN
(SELECT DISTINCT tbraccd_pidm, SUM(tbraccd_amount)
-- tuition
FROM tbraccd, tbbcstu, spriden
WHERE tbraccd_term_code = '201010'
AND (tbraccd_detail_code = 'TU01' OR
tbraccd_detail_code = 'TU02' OR
tbraccd_detail_code = 'TU03' OR
tbraccd_detail_code = 'TU04')
AND tbraccd_pidm = tbbcstu_stu_pidm
AND tbraccd_pidm = spriden_pidm
GROUP BY tbraccd_pidm)
--this code works up to this point
--when I add the next query I get nothing
AND (tbraccd_pidm, tbraccd_amount) IN
(SELECT tbraccd_pidm, SUM(tbraccd_amount)
books
FROM tbraccd, tbbcstu
WHERE tbraccd_term_code = '201010'
AND (tbraccd_detail_code = 'BKSU' OR
tbraccd_detail_code = 'BKCH')
AND tbraccd_pidm = tbbcstu_stu_pidm
GROUP BY tbraccd_pidm, tbraccd_amount)
--AND (tbraccd_pidm, tbraccd_amount) IN
-- (SELECT tbraccd_pidm, SUM(tbraccd_amount)
-- misc
-- FROM tbraccd, tbbcstu
-- WHERE tbraccd_term_code = '201010'
-- AND tbraccd_pidm = tbbcstu_stu_pidm
-- AND (tbraccd_detail_code = 'AUNA' OR
-- tbraccd_detail_code = 'OTPB')
-- GROUP BY tbraccd_pidm, tbraccd_amount)
--ORDER BY tbraccd_pidm, spriden_first_name, spriden_mi, spriden_last_name,
-- tbbcstu_sponsor_ref_number, sftregs_credit_hr;
ORDER BY tbraccd_pidm;
BEGIN
v_filehandle := utl_file.fopen(location => 'UTLFILE_MISAP9',
filename => 'ban_matrix.dat',
open_mode => 'w',
max_linesize => 32767);
OPEN c_sel_contract;
LOOP
DBMS_OUTPUT.PUT_LINE('looping');
FETCH c_sel_contract INTO v_contract_id, v_contract_name,
v_contract_addr1, v_contract_addr2,
v_contract_city, v_contract_stat,
v_contract_zip;
EXIT WHEN c_sel_contract%NOTFOUND;
v_output :=
nvl(rpad(v_contract_id,9),rpad(' ',9)) ||
' ' ||
nvl(rpad(v_contract_name,60),rpad(' ',60));
utl_file.put_line(v_filehandle,v_output);
v_output :=
nvl(rpad(v_contract_addr1, 30),rpad(' ',30)) ||
' ' ||
nvl(rpad(v_contract_addr2, 30),rpad(' ',30));
utl_file.put_line(v_filehandle,v_output);
v_output :=
nvl(rpad(v_contract_city, 20), rpad(' ',20)) ||
' ' ||
nvl(rpad(v_contract_stat, 3), rpad(' ',3)) ||
' ' ||
nvl(rpad(v_contract_zip, 10), rpad(' ',10));
utl_file.put_line(v_filehandle,v_output);
utl_file.new_line(v_filehandle);
OPEN c_sel_student;
LOOP
FETCH c_sel_student into v_student_id, v_student_first_name, v_student_mid_name,
v_student_last_name,
v_credit_hrs,
v_tuition_amount,
v_sftregs_pidm,
v_tbraccd_pidm;
-- v_books_amount, v_misc_amount;
EXIT WHEN c_sel_student%NOTFOUND;
v_last_out := substr(v_student_last_name, 1, 20);
v_output :=
nvl(rpad(v_student_id, 09),rpad(' ',09)) ||
' ' ||
nvl(rpad(v_student_first_name, 15),rpad(' ',15)) ||
nvl(rpad(v_student_mid_name, 15),rpad(' ',15)) ||
nvl(rpad(v_last_out, 20),rpad(' ',20)) ||
' ' ||
nvl(rpad(v_student_ref_number, 09),rpad(' ',09)) ||
' ' ||
v_credit_hrs ||
' ' ||
v_tuition_amount ||
-- v_books_amount ||
-- ' ' ||
-- v_misc_amount;
utl_file.put_line(v_filehandle,v_output);
END LOOP;
END LOOP;
--EXCEPTION
--WHEN OTHERS THEN
-- DECLARE
-- err_msg VARCHAR2(100);
-- BEGIN
-- err_msg := 'ERR- '||SUBSTR(SQLERRM, 1,100);
-- - utl_file.put_line(v_filehandle,err_msg);
--END;
utl_file.fclose(v_filehandle);
CLOSE c_sel_contract;
CLOSE c_sel_student;
--END AR_MATRIX_PROC;
END;run this original query
SELECT DISTINCT spriden_id,
spriden_first_name,
spriden_mi,
spriden_last_name,
sftregs_credit_hr,
tbraccd_amount,
sftregs_pidm,
tbraccd_pidm
FROM spriden, tbraccd, tbbcstu, sftregs
WHERE 559220 = tbbcstu_contract_pidm
AND spriden_pidm = tbraccd_pidm
AND spriden_pidm = tbbcstu_stu_pidm
AND spriden_pidm = sftregs_pidm
AND (sftregs_pidm, sftregs_credit_hr) IN (SELECT DISTINCT sftregs_pidm, SUM(sftregs_credit_hr)
FROM sftregs, tbbcstu, spriden
WHERE sftregs_term_code = '201010'
AND sftregs_pidm = tbbcstu_stu_pidm
AND sftregs_pidm = spriden_pidm
GROUP BY sftregs_pidm)
AND (tbraccd_pidm, tbraccd_amount) IN (SELECT DISTINCT tbraccd_pidm, SUM(tbraccd_amount)
-- tuition
FROM tbraccd, tbbcstu, spriden
WHERE tbraccd_term_code = '201010'
AND (tbraccd_detail_code = 'TU01' OR
tbraccd_detail_code = 'TU02' OR
tbraccd_detail_code = 'TU03' OR
tbraccd_detail_code = 'TU04')
AND tbraccd_pidm = tbbcstu_stu_pidm
AND tbraccd_pidm = spriden_pidm
GROUP BY tbraccd_pidm)
AND (tbraccd_pidm, tbraccd_amount) IN (SELECT tbraccd_pidm, SUM(tbraccd_amount) books
FROM tbraccd, tbbcstu
WHERE tbraccd_term_code = '201010'
AND (tbraccd_detail_code = 'BKSU' OR
tbraccd_detail_code = 'BKCH')
AND tbraccd_pidm = tbbcstu_stu_pidm
GROUP BY tbraccd_pidm, tbraccd_amount)
ORDER BY tbraccd_pidm;then run this sub-query:
SELECT tbraccd_pidm, SUM(tbraccd_amount) books
FROM tbraccd, tbbcstu
WHERE tbraccd_term_code = '201010'
AND (tbraccd_detail_code = 'BKSU' OR
tbraccd_detail_code = 'BKCH')
AND tbraccd_pidm = tbbcstu_stu_pidm
GROUP BY tbraccd_pidm, tbraccd_amount)see if you have a matching tbraccd_pidm and tbraccd_amount between the two results. -
Issue with the below query. The query is not getting filtered for the condition hier_typ_c in('BS') with the connect by prior
query. query is fetching all the hier_type_c in the table like 'BS', 'CO', 'EC' etc....
Just wondering how do i restrict the query just to fetch the type_c ='BS' alone? why is it giving all the records??
Select
Level as LEVEL_CODE,
h.HIER_PRNT_NODE_I as PARENT,
h.HIER_CHLD_NODE_I as CHILD,
h.HIER_CHLD_NODE_X || ' (' || h.HIER_CHLD_NODE_I || ')' as ALIAS
From (Select Distinct HIER_CHLD_NODE_I, HIER_PRNT_NODE_I,
HIER_CHLD_NODE_X from .HIER_DIMN
where hier_typ_c in('BS') and CURR_VER_C = 'Y') h
Start with h.HIER_PRNT_NODE_I = 'ROOT'
Connect by prior
h.HIER_CHLD_NODE_I = h.HIER_PRNT_NODE_I
Order by LEVEL_CODE, parent, childHi
It loks like you're doing it right.
By basing the CONNECT BY query on a sub-query that has this WHERE clasue:
where hier_typ_c in('BS') and CURR_VER_C = 'Y') hyou should exclude not only nodes whose hier_typ_c is not 'BS', but also their descendants.
Post some sample data (CREATE TABLE and INSERT statements) and the results you want from that data.
Are you sure the query you posted is what you're actually running?
I would expect the sub-query FROM clause to cause an error because of the '.'.
from .HIER_DIMNEdited by: Frank Kulash on Sep 29, 2009 11:16 AM -
Scoping violation in sub-query
I created a sql in Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 to query Oracle Purchasing tables. The user wants to know an estimate of the number of business days it takes to approve a release once it is created. I created a subquery as follows:
Select Papf.Full_Name As Approver
, Pah.Action_Date As Approved_Date
, Por.Creation_Date
, Trunc(Pah.Action_Date) - Trunc(Por.Creation_Date) As Days
, (Select Count(*)
From (Select Level, (Pah.Action_Date+1)-Level My_Date From Dual
Connect By Level < Trunc(Pah.Action_Date+1) - Trunc(por.creation_Date)
) Where To_Char(My_Date, 'DY') In ('MON', 'TUE', 'WED', 'THU', 'FRI')) As Days2Approve
FROM Apps.Po_Headers_All Poh
, Apps.Po_Releases_All Por
, Apps.Po_Lines_All Pol
, Apps.Po_Action_History Pah
…etc.
When I run the query I get the following error message:
ORA-00904: "POR"."CREATION_DATE": invalid identifier
00904. 00000 - "%s: invalid identifier"
*Cause:
*Action:
Error at Line: 193 Column: 54
I know the sub-query conceptually sound because if I run the sql below with dummy dates I get 17 which is correct.
Select Count(*)
From (SELECT level, (to_date('24-JAN-2013')+1)-level my_date From Dual
Connect By Level < Trunc(To_Date('24-JAN-2013')+1) - Trunc(To_Date('01-JAN-2013'))
) Where To_Char(My_Date, 'DY') In ('MON', 'TUE', 'WED', 'THU', 'FRI')
How do I pass Pah.Action_Date & por.creation_Date to the sub-query without getting what appears to be scoping violation?
…Hi,
You can avoid the problem by not using a nested sub-query:
SELECT COUNT (*)
FROM dual
CONNECT BY LEVEL < TRUNC (pah.action_date + 1)
- TRUNC (por.creation_date)
WHERE TO_CHAR ( pah.action_date + 1 - LEVEL
, 'DY'
) NOT IN ('SAT', 'SUN')
) AS days2approve
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
Explain, using specific examples, how you get those results from that data.
See the forum FAQ {message:id=9360002} -
See my query problem for sub query
hi master
Sir see my query
select lpad(' ',2*(level-1)) || to_char(chartofacc.child),parent,accid as accounted ,title,
case when fstatus=1 then
(select sum(drbal) from accbal where parent = accounted)
when fstatus is null then
(select drbal from accbal where accid = accounted)
end subtotal
from chartofacc
start with chartofacc.parent is null
connect by prior chartofacc.child = chartofacc.parent order by chartofacc.accid
I try but not success how I pass main query value or code in sub query or inner query
My requirement is inner query get total from accbal table how have accid that in main query accid or accounted
How I pass main query value or accid code to inner query and inner query give result as per main query accid
How I get subtotal and total by one query
Please give me idea or code
Thanking you
aamirYou could write your main SELECT statement as inline view or use the WITH clause, like this:
WITH ctf AS (SELECT LPAD (' ', 2 * (LEVEL - 1)) || TO_CHAR (chartofacc.CHILD), PARENT,
accid AS accounted, title,
FROM chartofacc
START WITH chartofacc.PARENT IS NULL
CONNECT BY PRIOR chartofacc.CHILD = chartofacc.PARENT
ORDER BY chartofacc.accid
SELECT ctf.*,
CASE WHEN fstatus = 1
THEN (SELECT SUM (drbal)
FROM accbal
WHERE PARENT = accounted)
WHEN fstatus IS NULL
THEN (SELECT drbal
FROM accbal
WHERE accid = accounted)
END subtotal
FROM ctf
not tested
C. -
Recursive Sub-query Factoring vs Hierarchical Query
Experts,
The below are two queries i am executing by using classical approach hierarchical and newest recursive sub-query.Problem is output was different for recursive sub-query factoring, as this is not showing parent-child approach, while connect by prior is showing parent-child fashion.Query 1, i am using hierarchical as it showing correct output parent-child approach, while Query 2 is displaying all the level 1 nodes and then level 2 nodes.I want query 2 output to be same as query 1.Please modify query 2 as required.
Note:The output of the both queries won't be in displayed as it was in sqlplus, or toad.Please copy and use in your command prompts.
QUERY 1:
with main as(select 1 id,'john' name,null mgrid from dual union all
select 2 id,'michael' name,null mgrid from dual union all
select 3 id,'peter' name,null mgrid from dual union all
select 4 id,'henry' name,1 mgrid from dual union all
select 5 id,'nick' name,2 mgrid from dual union all
select 6 id,'pao' name,3 mgrid from dual union all
select 7 id,'kumar' name,3 mgrid from dual union all
select 8 id,'parker' name,3 mgrid from dual union all
select 9 id,'mike' name,5 mgrid from dual),
select lpad(' ',2*(level-1))||name name,level from main start with mgrid is null connect by prior id=mgrid;
OUTPUT :
NAME LEVEL
john 1
henry 2
michael 1
nick 2
mike 3
peter 1
pao 2
kumar 2
parker 2
9 rows selected.
QUERY 2:
with main as(select 1 id,'john' name,null mgrid from dual union all
select 2 id,'michael' name,null mgrid from dual union all
select 3 id,'peter' name,null mgrid from dual union all
select 4 id,'henry' name,1 mgrid from dual union all
select 5 id,'nick' name,2 mgrid from dual union all
select 6 id,'pao' name,3 mgrid from dual union all
select 7 id,'kumar' name,3 mgrid from dual union all
select 8 id,'parker' name,3 mgrid from dual union all
select 9 id,'mike' name,5 mgrid from dual),
/*select lpad(' ',2*(level-1))||name name,level from main start with mgrid is null connect by prior id=mgrid;*/
secmain (id,name,mgrid,hierlevel) as(select id,name,mgrid,1 hierlevel from main where mgrid is null
union all
select m.id,m.name,m.mgrid,sm.hierlevel+1 from main m join secmain sm on(m.mgrid=sm.id))
cycle id set is_cycle to 1 default 0
select lpad(' ',2*(hierlevel-1))||name name,hierlevel from secmain;
OUTPUT :
NAME HIERLEVEL
john 1
michael 1
peter 1
henry 2
nick 2
parker 2
kumar 2
pao 2
mike 3
9 rows selected.Hi,
What's wrong with Query 1? If it's producing the results you want, then why not use it?
One of the nice features of CONNECT BY is that the output is automatically presented in hierachical order. The only way I know of to get the results of a recursive WITH clause in any kind or order is to do it yourself. Here's one way:
WITH secmain (id, name, mgrid, hierlevel, path) AS
SELECT id
, name
, mgrid
, 1 AS hierlevel
, RPAD (name, 10) AS path -- Assuming name is never longer than 10
FROM main
WHERE mgrid IS NULL
UNION ALL
SELECT m.id
, m.name
, m.mgrid
, sm.hierlevel + 1
, sm.path || RPAD (name, 10)
FROM main m
JOIN secmain sm ON (m.mgrid = sm.id)
CYCLE id -- Why do you need this if CONNECT BY NOCYCLE wasn't needed in Query 1?
SET is_cycle TO 1
DEFAULT 0
SELECT lpad ( ' '
, 2 * (hierlevel - 1)
) || name AS name
, hierlevel
FROM secmain
ORDER BY path
;Sorry, I don't have an Oracle 11.2 database right now, so I can't test it.
Edited by: Frank Kulash on Nov 23, 2011 9:15 AM
I didn't know about the SEARCH clause, Use Dom's solution, above. -
Outter-Join with requirement for sub-query
I am working on a view that needs to return 1 record per payment date within the primary payment table.
Part of the information that is to be returned in this row comes from a date-controlled table containing superannuation information. This data may or may not be present, requiring an outer-join. The final problem is that there may be multiple rows in this superannuation table requiring me to retrieve the record with the most recent start date, prior to the payment date. This is where I'm breaking down currently as I cannot outer-join to a sub-query.
I had an idea that I could create an inline view of the superannuation table with 1 row for each of the last 365 days (The reports that will be built off the view are always run within 1-2 months of the payment date), with the date and either the required information or blanks if it did not exist. This would avoid me requiring an outer-join as I could just join on the payment date to the date in the inline query and return whatever data was there.
I'm pretty sure I should be able to do this with analytics rather than creating a date table, by restricting the rows to 365, then havign a column that is effectively the previous column - 1. Unfortunately I'm fairly new to analytics and find the Oracle documentation hard to decipher.
Can anyone help with this or perhaps suggest an alternate solution?please don't do that. that's the most pathetic way generate rows. all_objects is a very nasty view, and oracle reserves the right to merge the view into the rest of your query, making performance less than you had hoped for. how about this instead:
select ...
from (
select trunc(sysdate-rownum+1) super_date
from dual
connect by level < = 365 ) dates,
your_table_here
where dates.super_date = your_column (+)
... -
Urgent - Cannot run sub query from VB 6
Hello!
I'm having a problem with my Oracle OLE DB connection in windows using Visual Basic 6.0 SP3.
I can run normal queries just fine, but a correlated sub query like this:
select A.col_a, (select col_b from Tab_B where id = A.id) from Tab_A A
returns the following error:
"ORA-00907: missing right parenthesis"
But I'm able to run the query witout errors in Toad with the correct result!
So basically, I cannot run a (correlated?) sub query via OLE DB...
What am I doing wrong?? Is it a parameter that I need to set on the connection of command?
I'm not using stored procedures, only plain text SQL.
Very thankful for a quick answer, this is really urgent. If you have the possibility, please e-mail me at:
[email protected]
Thank you in advance.
Best regards,
Bnar BabanHi!
I'm running the latest version of Oracle OLE DB...when checking more in detail, it seems that the provider parses the code in a way, that makes the "(select" part of the sub statement be interpreted as a column name....when it does not find a right parenthesis, but a white space, it complains.
I switched to Microsoft MSDAORA provider, and now it works perfectly...
/Bnar -
How to get all rows that are returned in inner sub query of select statemen
If a sub query in select statement returns more than one row than how to get all those returned rows in the final
output of the query .It will be all right if all column's value repeat and that multiple output of inner query comes
in another column .
How to get that ?As Frank said, you likely want a join, and likely an outer join to replicate the select in the projection. Something like:
SELECT id,stat, section, USER_ID concerned_person
FROM table_all,
left join table2
on room_id = sectoion and
sur_role = 'r001'
WHERE section IN (SELECT code
FROM t_area
WHERE dept= 'p002')An alternative, depending on where and how you are using the statement would be something like:
SQL> WITH t AS (
2 select 1 id from dual union all
3 select 2 id from dual),
4 t1 as (
5 select 1 id, 'One' descr from dual union all
6 select 1, 'Un' from dual union all
7 select 1, 'Une' from dual)
8 SELECT t.id, CURSOR(SELECT t1.id, t1.descr from t1
9 WHERE t1.id = t.id)
10 FROM t;
ID CURSOR(SELECTT1.ID,T
1 CURSOR STATEMENT : 2
CURSOR STATEMENT : 2
ID DESCR
1 One
1 Un
1 Une
2 CURSOR STATEMENT : 2
CURSOR STATEMENT : 2
no rows selectedJohn -
Powershell use Connection String to query Database and write to Excel
Right now I have a powershell script that uses ODBC to query SQL Server 2008 / 2012 database and write to EXCEL
$excel = New-Object -Com Excel.Application
$excel.Visible = $True
$wb = $Excel.Workbooks.Add()
$ws = $wb.Worksheets.Item(1)
$ws.name = "GUP Download Activity"
$qt = $ws.QueryTables.Add("ODBC;DSN=$DSN;UID=$username;PWD=$password", $ws.Range("A1"), $SQL_Statement)
if ($qt.Refresh()){
$ws.Activate()
$ws.Select()
$excel.Rows.Item(1).HorizontalAlignment = $xlCenter
$excel.Rows.Item(1).VerticalAlignment = $xlTop
$excel.Rows.Item("1:1").Font.Name = "Calibri"
$excel.Rows.Item("1:1").Font.Size = 11
$excel.Rows.Item("1:1").Font.Bold = $true
$filename = "D:\Script\Reports\Status_$a.xlsx"
if (test-path $filename ) { rm $filename }
$wb.SaveAs($filename, $xlOpenXMLWorkbook) #save as an XML Workbook (xslx)
$wb.Saved = $True #flag it as being saved
$wb.Close() #close the document
$Excel.Quit() #and the instance of Excel
$wb = $Null #set all variables that point to Excel objects to null
$ws = $Null #makes sure Excel deflates
$Excel=$Null #let the air out
I would like to use connection string to query the database and write results to EXCEL, i.e.
$SQL_Statement = "SELECT ..."
$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Server=10.10.10.10;Initial Catalog=mydatabase;User Id=$username;Password=$password;"
$conn.Open()
$cmd = New-Object System.Data.SqlClient.SqlCommand($SQL_Statement,$conn)
do{
try{
$rdr = $cmd.ExecuteReader()
while ($rdr.read()){
$sql_output += ,@($rdr.GetValue(0), $rdr.GetValue(1))
$transactionComplete = $true
catch{
$transactionComplete = $false
}until ($transactionComplete)
$conn.Close()
How would I read the columns and data for $sql_output into an EXCEL worksheet. Where do I find these tutorials?Hi Q.P.Waverly,
If you mean to export the data in $sql_output to excel document, please try to format the output with psobject:
$sql_output=@()
do{
try{
$rdr = $cmd.ExecuteReader()
while ($rdr.read()){
$sql_output+=New-Object PSObject -Property @{data1 = $rdr.GetValue(0);data2 =$rdr.GetValue(1)}
$transactionComplete = $true
catch{
$transactionComplete = $false
}until ($transactionComplete)
$conn.Close()
Then please try to use the cmdlet "Export-Csv" to export the data to excel like:
$sql_output | Export-Csv d:\data.csv
Or you can export to worksheet like:
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$workbook = $excel.Workbooks.Add()
$sheet = $workbook.ActiveSheet
$counter = 0
$sql_output | ForEach-Object {
$counter++
$sheet.cells.Item($counter,1) = $_.data1$sheet.cells.Item($counter,2) = $_.data2}
Refer to:
PowerShell and Excel: Fast, Safe, and Reliable
If there is anything else regarding this issue, please feel free to post back.
Best Regards,
Anna Wang -
OFFICE 2013 - Word could not re-establish a DDE connection to Microsoft Query
Hi, I have installed office 2013 on a pc and used excel to run a query on a database and created a .qry query so I can use this data in word mail merge.
The query runs ok and returns the data.
However, when I go to take the data in through mail merge it comes up with a message "Confirm data source" ( I enabled this after reading kb article below) so I select "MS query files via DDE(*.qry, *.dqy)" as this is a .dqy I select
it. It says at the bottom of the screen word is starting query then comes up with the error "Word could not re-establish a DDE connection to Microsoft Query to complete the current task".
I have re-did the query from scratch and no difference I tried the recommend kb article 918594 and it still doesn't work.
I recreated the odbc link and still no joy.
Has anyone come across this and have they a solution I would be grateful.
Thanks
TomHi,
Try to check whether the methods listed in the following link is helpful. The link applies to previous versions, but we can refer to it.
http://support.microsoft.com/kb/813989
Jaynet Zhang
TechNet Community Support -
How to find out which sub query returns more than one row
Hi all,
Can any one give me clue ,how to find out which sub query returns more than one row in the following query .
/* Formatted on 2011/05/17 19:22 (Formatter Plus v4.8.8) */
SELECT a.*, ROWNUM AS rnm
FROM (SELECT DISTINCT '1' AS "Page View", ou.org_unit_name AS "Org",
prxm.mbr_idntfr AS "Beneficiary ID",
md.last_name
|| ', '
|| md.first_name AS "Beneficiary Name",
pci.idntfr AS "Tracking No.",
TO_CHAR (TRUNC (req.pa_rqst_date),
'MM/dd/yyyy'
) AS "Request Date",
sts.status_name AS "Status",
req.pa_rqst_sid AS "Request #",
prxm.mbr_sid AS "Mbr_sid",
TO_CHAR
(TRUNC (req.pa_revision_date),
'MM/dd/yyyy'
) AS "Last Updated",
TO_CHAR (psd.TO_DATE, 'MM/dd/yyyy') AS "TO_DATE",
prxpl.prvdr_lctn_iid AS "PRVDR_LCTN_IID",
pd.prvdr_sid AS "PRVDR_SID", 'Y' AS "State View",
DECODE
((SELECT DISTINCT pd.national_prvdr_idntfr
FROM pa_request_x_provider_location prxplo
WHERE prxplo.pa_rqst_sid =
req.pa_rqst_sid
AND prxplo.oprtnl_flag = 'A'
AND prxplo.pa_prvdr_type_lkpcd = 'RR'),
0, (SELECT prxplo.prvdr_lctn_idntfr
FROM pa_request_x_provider_location prxplo
WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid
AND prxplo.oprtnl_flag = 'A'
AND prxplo.pa_prvdr_type_lkpcd = 'RR'),
NULL, (SELECT prxplo.prvdr_lctn_idntfr
FROM pa_request_x_provider_location prxplo
WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid
AND prxplo.oprtnl_flag = 'A'
AND prxplo.pa_prvdr_type_lkpcd = 'RR'),
(SELECT DISTINCT pd.national_prvdr_idntfr
FROM pa_request_x_provider_location prxplo
WHERE prxplo.pa_rqst_sid =
req.pa_rqst_sid
AND prxplo.oprtnl_flag = 'A'
AND prxplo.pa_prvdr_type_lkpcd = 'RR')
) AS "NPI/ID",
DECODE
((SELECT pd.org_bsns_name
FROM pa_request_x_provider_location prxplo
WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid
AND prxplo.oprtnl_flag = 'A'
AND prxplo.pa_prvdr_type_lkpcd = 'RR'),
NULL, (SELECT pd.last_name
|| ', '
|| pd.first_name
|| ' '
|| pd.middle_name
FROM pa_request_x_provider_location prxplo
WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid
AND prxplo.oprtnl_flag = 'A'
AND prxplo.pa_prvdr_type_lkpcd = 'RR'),
(SELECT pd.org_bsns_name
FROM pa_request_x_provider_location prxplo
WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid
AND prxplo.oprtnl_flag = 'A'
AND prxplo.pa_prvdr_type_lkpcd = 'RR')
) AS "Prvdr Name",
TO_CHAR (psd.from_date,
'MM/dd/yyyy'
) AS "Srvc From Date",
TO_CHAR (req.validity_start_date,
'MM/DD/YYYY'
) AS "Due Date",
(fn_get_busniess_days (TRUNC (req.validity_start_date))
) AS "Days<br>Left",
req.pa_mode_type_lkpcd AS "Source",
TO_CHAR (TRUNC (wmdtl.rtng_date),
'MM/dd/yyyy'
) AS "Assigned On",
NVL (wmdtl.assigned_to_user_name,
'Not Assigned'
) AS "Assigned To",
req.org_unit_sid AS "OrgUnitSid",
TO_CHAR
(wmdtl.modified_date,
'MM/dd/yyyy hh24:mi:ss'
) AS "WTRD_MODIFIED_DATE",
TO_CHAR (wmdtl.rtng_date,
'MM/dd/yyyy'
) AS "WTRD_RTNG_DATE",
req.status_cid AS "PA_STATUS_CID",
TO_CHAR (req.modified_date,
'MM/dd/yyyy'
) AS "PA_REQ_MODIFIED_DATE",
prs.state_pa_srvc_type_code
AS "STATE_PA_SRVC_TYPE_CODE",
wmdtl.wm_pa_task_rtng_dtl_sid
AS "WM_TASK_RTNG_DTL_SID",
wmdtl.assigned_to_user_acct_sid
AS "WTRD_Assigned_to_user_acct_sid",
(fn_get_busniess_days (TRUNC (req.validity_start_date))
) AS "Days<br>LeftSort",
wmdtl.assigned_to_org_unit_sid
AS "WTRD_Assigned_to_OrgUntSid",
DECODE
((SELECT COUNT (*)
FROM pa_request_status prs
WHERE prs.pa_rqst_sid = req.pa_rqst_sid
AND prs.status_cid = 5
AND prs.oprtnl_flag = 'I'),
0, 'N',
'Y'
) AS "SHOW_UTILIZATION"
FROM pa_request req,
pa_certification_identifier pci,
status sts,
pa_request_x_member prxm,
wm_pa_task_routing_detail wmdtl,
pa_service_date psd,
org_unit ou,
pa_request_service prs,
pa_request_x_provider_location prxpl,
provider_location pl,
provider_detail pd,
provider p,
mbr_dmgrphc md
WHERE req.oprtnl_flag = 'A'
AND req.status_cid NOT IN
(20, 30, 70, 25, 80, 96, 85, 5, 97, 98, 101)
AND req.org_unit_sid IN
(3057, 3142, 3058, 3143, 3059, 3144, 3060, 3145,
3061, 3146, 3062, 3147, 3063, 3148, 3064, 3149,
3065, 3150, 3066, 3151, 3067, 3152, 3068, 3153,
3069, 3154, 3070, 3155, 3071, 3156, 3072, 3157,
3073, 3158, 3074, 3159, 3075, 3160, 3076, 3161,
3077, 3162, 3078, 3163, 3079, 3164, 3080, 3165,
3081, 3166, 3082, 3167, 3083, 3168, 3084, 3169,
3085, 3170, 3086, 3171, 3087, 3172, 3088, 3173,
3089, 3174, 3090, 3175, 3091, 3176, 3092, 3177,
3093, 3178, 3094, 3179, 3095, 3180, 3096, 3181,
3097, 3182, 3098, 3183, 3099, 3184, 3100, 3185,
3101, 3186, 3102, 3187, 3103, 3003, 75000104,
75000108, 2006, 75000103, 75000102, 75000113,
75000111, 75000109, 2001, 2009, 75000105,
75000107, 2004, 2010, 2013, 2014, 2005, 2011,
75000112, 2002, 1001, 2012, 75000106, 2007,
75000101, 2003, 75000110, 2008, 3001, 3002, 3019,
3104, 3020, 3105, 3021, 3106, 3022, 3107, 3023,
3108, 3024, 3109, 3025, 3110, 3026, 3111, 3027,
3112, 3028, 3113, 3029, 3114, 3030, 3115, 3031,
3116, 3032, 3117, 3033, 3118, 3034, 3119, 3035,
3120, 3036, 3121, 3037, 3122, 3038, 3123, 3039,
3124, 3040, 3125, 3041, 3126, 3042, 3127, 3043,
3128, 3044, 3129, 3045, 3130, 3046, 3131, 3047,
3132, 3048, 3133, 3049, 3134, 3050, 3135, 3051,
3136, 3052, 3137, 3053, 3138, 3054, 3139, 3055,
3140, 3056, 3141)
AND req.pa_rqst_sid = prs.pa_rqst_sid
AND prs.oprtnl_flag = 'A'
AND prs.pa_rqst_srvc_sid = psd.pa_rqst_srvc_sid
AND psd.oprtnl_flag = 'A'
AND req.pa_rqst_sid = pci.pa_rqst_sid
AND pci.oprtnl_flag = 'A'
AND req.pa_rqst_sid = prxm.pa_rqst_sid
AND prxm.oprtnl_flag = 'A'
AND md.oprtnl_flag = 'A'
AND md.status_cid = 2
AND TRUNC (SYSDATE) BETWEEN md.from_date AND md.TO_DATE
AND prxm.mbr_sid = md.mbr_sid
AND ou.org_unit_sid = req.org_unit_sid
AND ou.oprtnl_flag = 'A'
AND req.pa_rqst_sid = prxpl.pa_rqst_sid
AND prxm.pa_rqst_sid = prxpl.pa_rqst_sid
AND pci.pa_rqst_sid = prxm.pa_rqst_sid
AND pci.pa_rqst_sid = wmdtl.subsystem_task_sid
AND pci.pa_rqst_sid = prxpl.pa_rqst_sid
AND prxpl.pa_prvdr_type_lkpcd = 'RR'
AND prxpl.oprtnl_flag = 'A'
AND req.status_cid = sts.status_cid
AND sts.status_type_cid = 3
AND sts.oprtnl_flag = 'A'
AND prxpl.prvdr_lctn_iid = pl.prvdr_lctn_iid
AND p.prvdr_sid = pd.prvdr_sid
AND p.prvdr_sid = pl.prvdr_sid
AND pd.oprtnl_flag = 'A'
AND pd.status_cid = 2
AND TRUNC (SYSDATE) BETWEEN pd.from_date AND pd.TO_DATE
AND wmdtl.subsystem_task_sid = req.pa_rqst_sid
AND wmdtl.subsystem_lkpcd = 'PA'
AND wmdtl.oprtnl_flag = 'A'
AND req.pa_rqst_date > (SYSDATE - 365)
ORDER BY TO_DATE ("Request Date", 'MM/dd/yyyy hh24:mi:ss') DESC,
"Beneficiary Name" ASC) a
WHERE ROWNUM < 102;regards,
P Prakash
Edited by: BluShadow on 17-May-2011 15:01
added {noformat}{noformat} tags around the code833560 wrote:
Can any one give me clue ,how to find out which sub query returns more than one row in the following query .This is why smaller, simpler queries are easier to work with than huge ones - when something like this goes wrong smaller queries are much eaiser to debug. Unfortunately using smaller, easier-to-work with queries is not always an option
Ganesh is right - you will have to dissect the big query bit by bit until you find the offending subquery. If there is another way I would like to find out about it too.
The easiest way to do this is probably to use block comments to isolate parts of the query bit by bit until you find the offending part. If you carefully examine the subqueries you might be able to figure out which one is returning multiple rows without commenting everything
Good luck! -
How to use sub query in CAML in splist
hi,
want to know whether any sub query functionality can be achieved in splist/sp doc lib using CAML designer 2013/ query builder. also inner joins need to be implemented as pe rmy requirement.
if caml designer is not supported, whats the allternative way of doing this?
can LINQ to SP be used? if yes, can anyone pls roivde how to implement the same
help is appreciatedYou can use the let keyword to scope a variable containing the result of your subquery.
However, it depends on the LINQ provider as to whether or not it can understand the command.
For example, you can create the sample like this
var result = (from p in productInQuery
join o in orderInfoQuery on p.refNo equals o.refNo
join t in productOutQuery on p.no equals t.productInNo into productIn
from t in productIn.DefaultIfEmpty()
let dateOut = (from m in orderInfoQuery where m.refNo == t.refNo select m.processData).FirstOrDefault()
orderby o.processDate descending
select new
modelNo = x.modelNo,
qty = p.qty,
dateIn = o.processDate,
dateOut = dateOut
https://www.youtube.com/watch?v=N3K0h6GDwW4
For more info, check this
http://msdn.microsoft.com/en-us/library/ee539975.aspx -
Hi, I have two issues, here is my initial code:
select
cc.name_id_no
,cc.discover_date
,cc.cla_case_no
,max(rl.year_of_incident)Non_Loss_Past_5
,rl.timestamp
from cla_case cc, rbn_loss rl
where cc.name_id_no = rl.customer_no
and rl.year_of_incident < trunc(cc.discover_date)
and rl.type_of_loss < 1000
and rl.timestamp < trunc(cc.discover_date)
and (cc.question_class = 20
or cc.question_class = 25)
and (trunc(cc.discover_date)- (rl.year_of_incident)) < 1095
--and (trunc(cc.discover_date) <> (rl.year_of_incident))
group by cc.cla_case_no,name_id_no, cc.discover_date,rl.timestamp
Now a cla_case_no can map to several year_of_incident. I only want the cla_case_no that maps to the max year_of_incident ie There should only be a single cla_case_no corresponding to the max year_of_incident.
To get around this I did the following which is not very efficient and I'm hoping it can be improved:
select distinct z.cla_case_no from (
select
cc.name_id_no
,cc.discover_date
,cc.cla_case_no
,max(rl.year_of_incident)Non_MW_Loss_Past_5
,rl.timestamp
from cla_case cc, rbn_loss rl
where cc.name_id_no = rl.customer_no
and rl.year_of_incident < trunc(cc.discover_date)
and rl.type_of_loss < 1000
and rl.timestamp < trunc(cc.discover_date)
and (cc.question_class = 20
or cc.question_class = 25)
and (trunc(cc.discover_date)- (rl.year_of_incident)) < 1095
--and (trunc(cc.discover_date) <> (rl.year_of_incident))
group by cc.cla_case_no,name_id_no, cc.discover_date,rl.timestamp
) z
Now comes the second issue: The above is actually a subquery that will link to a bigger table via cla_case_no ccx
SELECT
ie ,(select distinct z.cla_case_no from (
select cc.name_id_no, cc.discover_date ,cc.cla_case_no, max(rl.year_of_incident)Non_MW_Loss_Past_5, rl.timestamp
from cla_case cc, rbn_loss rl
where cc.name_id_no = rl.customer_no
and rl.year_of_incident < trunc(cc.discover_date)
and rl.type_of_loss < 1000
and rl.timestamp < trunc(cc.discover_date)
and (cc.question_class = 20
or cc.question_class = 25)
and (trunc(cc.discover_date)- (rl.year_of_incident)) < 1095
--and (trunc(cc.discover_date) <> (rl.year_of_incident))
group by cc.cla_case_no,name_id_no, cc.discover_date,rl.timestamp
) z
where z.cla_case_no = ccx.cla_case_no
) Non_MW_Loss_Past_5
FROM etc
Now only certain cc.cla_case_no from the subquery will corresp to the ccx_cla_case_no from the main table and the other entries will be null.
What I require is that if the subquery returns a result that IS NOT NULL to return 'Y' ELSE 'N' instead of the varies cla_case_no's and (null) entries in the Non_MW_Loss_Past_5 column
Thanks!!!
Banner:
Oracle Database 11g Release 11.2.0.2.0 - 64bit Production
PL/SQL Release 11.2.0.2.0 - Production
"CORE 11.2.0.2.0 Production"
TNS for Linux: Version 11.2.0.2.0 - Production
NLSRTL Version 11.2.0.2.0 - ProductionHi,
It looks like you have another copy of this question:
Case Statement and sub query
That's probably not your fault, but you should mark the other copy as "Answered" right away, and then you'll only have to look for replies in one place.
885178 wrote:
... Now a cla_case_no can map to several year_of_incident. I only want the cla_case_no that maps to the max year_of_incident ie There should only be a single cla_case_no corresponding to the max year_of_incident.If you know there will only be one, then you can use LAST, and you don't need GrOUP BY
To get around this I did the following which is not very efficient and I'm hoping it can be improved:
select distinct z.cla_case_no from (
select
cc.name_id_no
,cc.discover_date
,cc.cla_case_no
,max(rl.year_of_incident)Non_MW_Loss_Past_5
,rl.timestamp
from cla_case cc, rbn_loss rl
where cc.name_id_no = rl.customer_no
and rl.year_of_incident < trunc(cc.discover_date)
and rl.type_of_loss < 1000
and rl.timestamp < trunc(cc.discover_date)
and (cc.question_class = 20
or cc.question_class = 25)
and (trunc(cc.discover_date)- (rl.year_of_incident)) < 1095
--and (trunc(cc.discover_date) <> (rl.year_of_incident))
group by cc.cla_case_no,name_id_no, cc.discover_date,rl.timestamp
) zHere's one way:
SELECT MIN (cla_case_no) KEEP (DENSE_RANK LAST ORDER BY r1.year_of_incident)
AS latest_cla_case_no
FROM cla_case cc
, rbn_loss rl
WHERE cc.name_id_no = rl.customer_no
AND rl.year_of_incident > TRUNC (cc.discover_date) - 1095
AND rl.year_of_incident < TRUNC (cc.discover_date)
AND rl.type_of_loss < 1000
AND rl.timestamp < TRUNC (cc.discover_date)
AND cc.question_class IN (20, 25)
;If you'd post some sample data (CREATE TABLE and INSERT statements) and the results you want from that data, then I could test this.
Now comes the second issue: The above is actually a subquery that will link to a bigger table via cla_case_no ccx
SELECT
ie ,(select distinct z.cla_case_no from (
select cc.name_id_no, cc.discover_date ,cc.cla_case_no, max(rl.year_of_incident)Non_MW_Loss_Past_5, rl.timestamp
from cla_case cc, rbn_loss rl
where cc.name_id_no = rl.customer_no
and rl.year_of_incident < trunc(cc.discover_date)
and rl.type_of_loss < 1000
and rl.timestamp < trunc(cc.discover_date)
and (cc.question_class = 20
or cc.question_class = 25)
and (trunc(cc.discover_date)- (rl.year_of_incident)) < 1095
--and (trunc(cc.discover_date) <> (rl.year_of_incident))
group by cc.cla_case_no,name_id_no, cc.discover_date,rl.timestamp
) z
where z.cla_case_no = ccx.cla_case_no
) Non_MW_Loss_Past_5
FROM etc
Now only certain cc.cla_case_no from the subquery will corresp to the ccx_cla_case_no from the main table and the other entries will be null.
What I require is that if the subquery returns a result that IS NOT NULL to return 'Y' ELSE 'N' instead of the varies cla_case_no's and (null) entries in the Non_MW_Loss_Past_5 column
NVL2 (x, 'Y', 'N')returns 'Y' if x is NULL, and it returns 'N' if x is not NULL. X can be a scalar sub-query:
NVL2 ((SELECT ...), 'Y', 'N')You could also use an EXISTS sub-query:
CASE
WHEN EXISTS (SELECT ...)
THEN 'Y'
ELSE 'N'
END -
Hi,
Can we use order by clause in Sub query?
While using the order by clause, I am getting the "missing expression error" . If I remove order by clause query executing fine.
Here is my query:
select *
from emp_mstr
where emp_no in(select
emp_no
from emp_mstr
order by branch_no);
Thanks & Regards,
MahiMay be you miss some required spaces also, other than wrong use of ORDER BY
select *
from emp_mstr
where emp_no in
( select e2.emp_no
from emp_mstr e2
-- order by e2.branch_no
);Why do you want to ORDER BY in the subquery, which you use with IN clause? That will not make any difference in the result..Means the result you get with ORDER BY will be same as without that.. And in this case, ORDER by is a unncessary overhead.. And Ordering is very costly..
And why do you want to have the IN clause at all in your query? You are referring the same tables in the main query and sub query..
The below will give the same result
select *
from emp_mstr
where emp_no is not nullIf you want to use another table in the subquery, always use aliasess...
select *
from emp_mstr
where emp_no in
( select e2.emp_no
from emp_mstr2 e2
-- order by e2.branch_no
);
Maybe you are looking for
-
ITunes library and my external hard drive
My iTunes library is on an external hard drive (for well over a year with no problems). All of a sudden, my laptop/iTunes can't locate the files unless I manually go into the HD and find it. How do I get my laptop to automatically read the library?
-
Do I need to specify VRF management for NX5020 management config?
I have a isolated NX5020 that only connects servers to storage controllers. It doesn't have any data traffic going into the network. The only connectivity to the network is through mgmt0 port. In this case, when I configure management functions such
-
There is a link with someone else who was receiving the same error, but i believe for different reasons. http://social.technet.microsoft.com/Forums/en-US/outlook/thread/43221dbf-60e1-4afb-8c25-f23f06deed3e I just performed an upgrade from office 2007
-
SAP Scripts for Stock Removal and Stock Placement ?
Hi All, Can you please let me know what are the SAP script names and Transaction codes for Stock Removal and Stock Placements ? Thanks, Raj
-
Defining Multiple Groups in PDF template
Hi, I am having trouble defining multiple groups in my pdf template. I would like to set up multiple groups for printing po data such as (G_LINES, G_SHIPMENTS, etc.) How is this done in Acrobat? I am using 7.0 Professional. I have created BODY START