How to write a sql query to calculate weights using CTE
Hi guys,
want some help using a CTE to generate data using recursive SQL - input data in table A to be transformed into table B shown below
Table A
Instru_id_index instru_id_name instru_id_constit con_name weight
56 INDEX A
23 A 25
56 INDEX A
24 B 25
56 INDEX A
25 C 25
56 INDEX A
57
INDEX B 25
57
INDEX B 31
D 33
57
INDEX B 32
E 33
57
INDEX B 33
F 33
(Logic should be recursive in order to be able to handle multi-level, not just level 2.)
Table B
Instru_id_index instru_id_name instru_id_constit constit_name weight
56 INDEX A
23 A 25
56 INDEX A
24 B 25
56 INDEX A
25 C 25
56 INDEX A
31 D 8.3
56 INDEX A
32 E 8.3
56 INDEX A
33 F 8.3
57
INDEX B 31
D 33
57
INDEX B 32 E
33
57
INDEX B 33
F 33
how can I write a simple CTE construct to display the data in table B - How can i calculate the values of weights as 8.3 respectively - calculate these without changing the structure of the tables.
Can I do this in a CTE
Full join?
Anyway, thanks for Rsignh to produces a script with CREATE TABLE and INSERT statements. I've extended the data to one more level of recursion.
create table weight_tab(
instrument_id_index int,
instrument_id_name varchar(10),
instrument_id_constituent int,
constituent_name varchar(10),
[weight] decimal(10,2))
insert into weight_tab values
(56,'INDEX A',23,'A',25),(56,'INDEX A', 24,'B',25),
(56,'INDEX A',25,'C',25),(56,'INDEX A', 57,'INDEX B',25),
(57,'INDEX B',31,'D',33), (57,'INDEX B', 32,'INDEX E',33),
(57,'INDEX B',33,'INDEX C',33),
(33,'INDEX C',42,'Alfa',60),
(33,'INDEX C',43,'Beta',40),
(32,'INDEX C',142,'Gamma',90),
(32,'INDEX C',143,'Delta',10)
go
SELECT * FROM weight_tab
go
; WITH rekurs AS (
SELECT instrument_id_index, instrument_id_name, instrument_id_constituent,
cast(weight as float) AS weight, cnt = 1
FROM weight_tab a
WHERE NOT EXISTS (SELECT *
FROM weight_tab b
WHERE b.instrument_id_constituent = a.instrument_id_index)
UNION ALL
SELECT r.instrument_id_index, r.instrument_id_name, w.instrument_id_constituent,
r.weight * w.weight / 100, r.cnt + 1
FROM rekurs r
JOIN weight_tab w ON r.instrument_id_constituent = w.instrument_id_index
WHERE r.cnt < 4
SELECT instrument_id_index, instrument_id_name, instrument_id_constituent,
cast(weight AS decimal(10,2))
FROM rekurs
go
DROP TABLE weight_tab
Erland Sommarskog, SQL Server MVP, [email protected]
Similar Messages
-
How to write a SQL query in SAP B1 2007 B with input parameters?
How to write a SQL query in SAP B1 2007 B with input parameters, on execution of which will ask for some input value from the user and the values will be selected from a list such as item list?
The syntax like
SELECT * FROM OITM T0 WHERE T0.ItemCode = '[%0\]'
Thanks,
Gordon -
How to write a sql query to retrieve data entered in the past 2 weeks
Hi,
I have file names and last accessed date(java.sql.Date format) stored in my database table, I would like to know how I can write a query to get the name of files accessed in the past 2 weeks,I use open sql server at the back end.
Thanks in advance.This has essentially nothing to do with JDBC. JDBC is just an API to execute the SQL language using Java and thus interact with the databases.
Your problem is related to the SQL language, you don't know how to write the SQL language. I suggest you to go through a SQL tutorial (there is one at w3schools.com) and to read the SQL documentation which come along with the database in question. A decent database manfacturer has a website and probably also a discussion forum / mailinglist as well.
I'll give you a hint: you can just use equality operators in SQL like everywhere. For example: "WHERE date < somedate". -
How to write this sql query in php code ?
for example:
insert into temp
select *
from testtable;
after this, i will query data from sql below:
select *
from temp;
how to write this php code ?
who can help me ?
thanks!Have a look at the manual to find out how to issue queries.
http://us3.php.net/oci8 -
We have a table, the structure as below: (I put a blank row in the middle to make it clear)
Product_ID Retailer Retail_Price
1001 A 1.2
1001 B 1.5
1001 C 1.4
1002 B 2.0
1002 C 2.1
1002 E 1.8
1002 F 2.0
1003 A 1.7
1003 C 1.5
Basically we use the table to compare the retail price for different retailers in terms of different products. My customer asked me to give a report based on above table but only shows the retail prices which contain retailer A.
For example, on above table I need to give a report like below:
Product_ID Retailer Retail_Price
1001 A 1.2
1001 B 1.5
1001 C 1.4
1003 A 1.7
1003 C 1.5
Can anybody give some ideas on how I should write a SQL to achieve this.
Many thanks!SQL> create table product(
2 Product_ID varchar2(10),
3 Retailer varchar2(10),
4 Retail_Price number(7,2)
5 )
6 /
Table created.
SQL> insert into product values('1001','A',1.2)
2 /
1 row created.
SQL> insert into product values('1001','B',1.5)
2 /
1 row created.
SQL> insert into product values('1001','C',1.4)
2 /
1 row created.
SQL> insert into product values('1002','B',2.0)
2 /
1 row created.
SQL> insert into product values('1002','C',2.1)
2 /
1 row created.
SQL> insert into product values('1002','E',1.8)
2 /
1 row created.
SQL> insert into product values('1002','F',2.0)
2 /
1 row created.
SQL> insert into product values('1003','A',1.7)
2 /
1 row created.
SQL> insert into product values('1003','C',1.5)
2 /
1 row created.
SQL> select * from product
2 /
PRODUCT_ID RETAILER RETAIL_PRICE
1001 A 1.2
1001 B 1.5
1001 C 1.4
1002 B 2
1002 C 2.1
1002 E 1.8
1002 F 2
1003 A 1.7
1003 C 1.5
9 rows selected.
SQL> select * from product where PRODUCT_ID in (
2 select distinct PRODUCT_ID from product where RETAILER='A')
3 /
PRODUCT_ID RETAILER RETAIL_PRICE
1001 A 1.2
1001 B 1.5
1001 C 1.4
1003 A 1.7
1003 C 1.5 -
How To Write A Sql Query to Show 0's
I never can remember this :-/ What do I have to do to get a SQL Query to return 0 if the Count of a condition is 0? For example lets say Joe, Jay, Jim could log on, but only Joe & Jim logged in Jay would not be returned in the query below. What
would I need to set-up so that All 3 users would be returned
Select logonName, Count(Logon)
From logonUserInfo
where logonName is not nullGROUP BY logonNameCurrently there is only 1 table involved. I would need a separate table? What would this table need to hold?
You wouldn't need a separate table unless and until you want to store who logged in at what time and so on... then your table structures looks like below..
CREATE TABLE loginnames
loginid INT
name VARCHAR(30),
GO
CREATE TABLE loginTimes
loginid INT,
logintime DATETIME
GO
So, now you can do a left join on both tables on a certain date directly and find out who actually logined and who didn't with a count 0 for the one's who didn't login... and that will abide the principles of normalization as well...
If you don't want to use an another table, you would have to duplicate the loginnames everytime that user logins and also you don't have a track on what date the login happened.. So you will be considering from day 1 to Till date...
Please mark as answer, if this has helped you solve the issue.
Good Luck :) .. visit www.sqlsaga.com for more t-sql code snippets and BI related how to articles. -
How to write a SQL Query without using group by clause
Hi,
Can anyone help me to find out if there is a approach to build a SQL Query without using group by clause.
Please site an example if is it so,
RegardsI hope this example could illuminate danepc on is problem.
CREATE or replace TYPE MY_ARRAY AS TABLE OF INTEGER
CREATE OR REPLACE FUNCTION GET_ARR return my_array
as
arr my_array;
begin
arr := my_array();
for i in 1..10 loop
arr.extend;
arr(i) := i mod 7;
end loop;
return arr;
end;
select column_value
from table(get_arr)
order by column_value;
select column_value,count(*) occurences
from table(get_arr)
group by column_value
order by column_value;And the output should be something like this:
SQL> CREATE or replace TYPE MY_ARRAY AS TABLE OF INTEGER
2 /
Tipo creato.
SQL>
SQL> CREATE OR REPLACE FUNCTION GET_ARR return my_array
2 as
3 arr my_array;
4 begin
5 arr := my_array();
6 for i in 1..10 loop
7 arr.extend;
8 arr(i) := i mod 7;
9 end loop;
10 return arr;
11 end;
12 /
Funzione creata.
SQL>
SQL>
SQL> select column_value
2 from table(get_arr)
3 order by column_value;
COLUMN_VALUE
0
1
1
2
2
3
3
4
5
6
Selezionate 10 righe.
SQL>
SQL> select column_value,count(*) occurences
2 from table(get_arr)
3 group by column_value
4 order by column_value;
COLUMN_VALUE OCCURENCES
0 1
1 2
2 2
3 2
4 1
5 1
6 1
Selezionate 7 righe.
SQL> Bye Alessandro -
How to write a sql query for this condition?
i have one table with columns v_sub,v_visit and v_date and the structure is like this
v_sub v_visit v_date
1 visit-1 01-mar-09
1 visit-2 05-mar-09
1 visit-3 17-mar-09
2 visit-1 04-feb-09
2 visit-2 12-mar-09
2 visit-3 20-mar-09
i want to write a query which check weather it is in chronological order or not.(for v_sub,v_visit and v_date should be in chronological order as above)
and i want to check the condition as below:
v_sub v_visit v_date
1 visit-1 01-mar-09
1 visit-2 05-feb-09
1 visit-3 17-mar-09
2 visit-1 04-feb-09
2 visit-2 12-jan-09
2 visit-3 20-mar-09
Thanks in advanceuse LAG function to get the previous date
SQL> -- sample data
SQL> with t
2 as
3 (
4 select 1 v_sub, 'visit-1' v_visit, to_date('01-mar-09','dd-mon-yy') v_date from dual union all
5 select 1, 'visit-2', to_date('05-mar-09','dd-mon-yy') from dual union all
6 select 1, 'visit-3', to_date('17-mar-09','dd-mon-yy') from dual union all
7 select 2, 'visit-1', to_date('04-feb-09','dd-mon-yy') from dual union all
8 select 2, 'visit-2', to_date('12-mar-09','dd-mon-yy') from dual union all
9 select 2, 'visit-3', to_date('20-mar-09','dd-mon-yy') from dual
10 )
11 -- end of sample data
12 select v_sub, v_visit, v_date, lag(v_date) over(partition by v_sub order by v_visit, v_date) v_previous_date
13 from t
14 /
V_SUB V_VISIT V_DATE V_PREVIOU
1 visit-1 01-MAR-09
1 visit-2 05-MAR-09 01-MAR-09
1 visit-3 17-MAR-09 05-MAR-09
2 visit-1 04-FEB-09
2 visit-2 12-MAR-09 04-FEB-09
2 visit-3 20-MAR-09 12-MAR-09
6 rows selected.Now you can check if the previous_date is less than v_date -
How to write a SQL query in Java
Hi, I'm writing a program that pulls all data from the database with a simple "SELECT * FROM [TABLE NAME]. The problem is that I don't know how to set it up properly. My code will only connect to the database but not execute the query. Please help.
{code}import java.sql.*;
import java.util.Properties;
import java.sql.*;
public class DatabaseSelect {
public static void main(String[] args) {
System.out.println("Connected to the database!");
Connection conn = null;
String url = "jdbc:oracle://localhost:1571/";
String dbName = "jdbc";
String driver = "com.oracle.jdbc.Driver";
String userName = "HR";
String password = "database";
String query = "SELECT * FROM HR";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
} catch (Exception e) {
e.printStackTrace();
}{code}pbsacct_1 wrote:
I added it between my System.out statement and the catch exception. This is what I put, but I'm getting the same result. I looks like a lot of errors. The only thing that prints is the "Connected to database".
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery("SELECT * FROM HR");Here is what displays in the console.
Connected to the database!
java.lang.ClassNotFoundException: com.oracle.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:164)
at Discussion10.DatabaseSelect.main(DatabaseSelect.java:26)You are not connecting.
Because you aren't even loading the driver.
To be honest if you can't decipher a stack trace with "java.lang.ClassNotFoundException" on your own you are not ready for JDBC anyway. -
How to write this sql query to oracle
Hi sir,
i am using one query in my sql stored procedure that is:
select @maxtime=CONVERT(Time,Out_Time+DATEADD(n,60,0)) from shift where Shift_Code = @ShiftCode
so here i am getting this value 01/01/1900 12:00 AM
the same i used in oracle my query is :
to_char(Out_Time,'1900-01-01' + 0/(24*60),'DD/MM/YYYY HH:MI AM')
INTO v_maxtime
FROM shift
WHERE Shift_Code = v_ShiftCode;
but getting error that is: Encountered the symbol INTO when expecting one of the following :=(%;
am i doing any thing wrong.
thanksAPC wrote:
The error you're getting is a syntax error. In this case because you've mangled the TO_CHAR syntax. Alas I cannot give you the correct version because I cannot unpick what you're trying to do with that statement.
It would be easier if you expalined what business logic you're trying to implement instead of asking us to interpret a piece of shonky SQL.It's yet another of the OP's questions about how to do DATEs in Oracle (so many threads it can get very confusing - even though the OP has been asked to stick to one thread!).
The code looks like it's based on the answer I gave here:
How to get exact query of sql in oracle?
but clearly he doesn't understand the basic syntax of Oracle or the datatypes he's using. Sometimes you just have to give up... (I know I have) -
Hi,
My table is similar to the below table. In the below table each case has one or more hometowns. But I need only one hometown for each case for that it has to select most recently (column date_mod)date if a case has two same (column date_mod) then it has to take maximum (column number)
For example in the below case for Case A it has same date_mod columns then it has to take maximum number which is 4. So the hometown for case A is Fairfiled so I have to select this hometown and I should ignore remaining hometowns. How to do this?
Case Name number date_mod hometown
A Rob Brooklyn
A Rob 4 01/09/2009 Fairfield
A Rob 3 01/09/2009 Newyork
B Well 14 01/11/2008 Charlotte
B Well Jackson
C John Elizabeth
D Douglas 25 11/11/2008 Ossising
D Douglas 27 03/03/2009 Ossiising
ThanksWhat about this:
SQL > WITH cases AS
2 (
3 SELECT 'A' AS CASE, 'Rob' AS NAME, NULL AS NUMB, NULL AS DATE_MOD, 'Brooklyn' AS HOMETOWN FROM DUAL UNION ALL
4 SELECT 'A' AS CASE, 'Rob' AS NAME, 4 AS NUMB, TO_DATE('01/09/2009','MM/DD/YYYY') AS DATE_MOD, 'Fairfield' AS HOMETOWN FROM DUAL UNION ALL
5 SELECT 'A' AS CASE, 'Rob' AS NAME, 3 AS NUMB, TO_DATE('01/09/2009','MM/DD/YYYY') AS DATE_MOD, 'Newyork' AS HOMETOWN FROM DUAL UNION ALL
6 SELECT 'D' AS CASE, 'Douglas' AS NAME, 25 AS NUMB, TO_DATE('11/11/2008','MM/DD/YYYY') AS DATE_MOD, 'Brooklyn' AS HOMETOWN FROM DUAL UNION ALL
7 SELECT 'D' AS CASE, 'Douglas' AS NAME, 27 AS NUMB, TO_DATE('03/03/2009','MM/DD/YYYY') AS DATE_MOD, 'Fairfield' AS HOMETOWN FROM DUAL
8 )
9 SELECT CASE
10 , NAME
11 , NUMB
12 , DATE_MOD
13 , HOMETOWN
14 FROM
15 (
16 SELECT CASE
17 , NAME
18 , NUMB
19 , DATE_MOD
20 , HOMETOWN
21 , row_number() OVER (PARTITION BY CASE ORDER BY DATE_MOD DESC NULLS LAST, NUMB DESC NULLS LAST) rn
22 FROM CASES
23 )
24 WHERE rn=1;
C NAME NUMB DATE_MOD HOMETOWN
A Rob 4 01/09/2009 00:00:00 Fairfield
D Douglas 27 03/03/2009 00:00:00 Fairfield -
Test(Table)
aaa
17.123
17.42
17.1234567
17.123456
i want to get the values whose precision is >6 i.e i should get 17.1234567
because when executing a stor proc iam getting ORA-6502 error
Thanks in advanceHi
Here is my query-- which is placed ina stored proc
o_Error_Text := 'Error in updating GRANT_VEST_ESTM_AMRTZN redistributing the overlapping expense ' ;
EXECUTE IMMEDIATE 'UPDATE GRANT_VEST_ESTM_AMRTZN
SET GRN_ESTM_TRNCHE_EXPS_Y = :1,
GRN_AMRTN_ORIGL_TRNCHE_EXPS_Y = :2,
GRN_VEST_ADJST_OPT_Q = :3
WHERE ORG_GRP_I = :4
AND GRN_N = :5
AND GRN_VEST_D = :6'
USING V_GRN_ESTM_TRNCHE_EXPS_Y(I), V_GRN_AMRTN_ORIG_TRNC_EXP_Y(I), V_GRN_VEST_NEW_ADJST_OPT_Q(I),
I_ORG_GRP_I, NEW_GRN(I), V_GRN_VEST_D(I);
V_GRN_ESTM_TRNCHE_EXPS_Y(I) are calculated based on some conditions
for example
V_GRN_ESTM_TRNCHE_EXPS_Y (I) := V_GRN_ESTM_TRNCHE_EXPS_Y(I) +
( (V_REM_GRN_VEST_ORIGL_OPT_Q(I) / V_GRN_VEST_OLD_ORIGL_OPT_Q(J)) * V_GRN_ESTM_EXPS_Y(J));
V_GRN_AMRTN_ORIG_TRNC_EXP_Y(I) := V_GRN_AMRTN_ORIG_TRNC_EXP_Y(I) +
( (V_REM_GRN_VEST_ORIGL_OPT_Q(I) / V_GRN_VEST_OLD_ORIGL_OPT_Q(J)) * V_GRN_ESTM_ORIGL_A(J));
V_GRN_VEST_NEW_ADJST_OPT_Q(I) := V_GRN_VEST_NEW_ADJST_OPT_Q(I) +
( (V_REM_GRN_VEST_ORIGL_OPT_Q(I) / V_GRN_VEST_OLD_ORIGL_OPT_Q(J)) * V_GRN_VEST_OLD_ADJST_OPT_Q(J));
V_REM_GRN_VEST_OLD_ORIGL_OPT_Q(J) := V_GRN_VEST_OLD_ORIGL_OPT_Q(J) - V_REM_GRN_VEST_ORIGL_OPT_Q(I);
V_REM_GRN_VEST_ORIGL_OPT_Q(I) := 0;
i got the error like this, which i checked from the error log table
error in updating grant_vest_estm_amrtzn redistributing the overlapping expense ORA-06502:PL/SQL numeric or value error
Looking forward for the response -
How to write the SQL query for generating triangular numbers
Hi,
I have a table ..which stores the sequence number like this
Seq :
1000
1200
1300
1500
1800
1900
Now i want to get a result like this
1000 1000
1200 2200
1300 3500
1500 5000
1800 6800
1900 8700
how can it be achieved. I tried using Lead and lag. but only I can add the n+1 or n-1 results. Please help.I've never heard it called 'triangular numbers' before but I think you're looking for a 'running total':
SQL> WITH data AS
2 (
3 SELECT 1000 AS num FROM dual UNION ALL
4 SELECT 1200 AS num FROM dual UNION ALL
5 SELECT 1300 AS num FROM dual UNION ALL
6 SELECT 1500 AS num FROM dual UNION ALL
7 SELECT 1800 AS num FROM dual UNION ALL
8 SELECT 1900 AS num FROM dual
9 )
10 /* END SAMPLE DATA */
11 SELECT num, SUM(num) OVER (ORDER BY num) AS running_total
12 FROM data
13 ORDER BY 1
14 ;
NUM RUNNING_TOTAL
1000 1000
1200 2200
1300 3500
1500 5000
1800 6800
1900 8700
6 rows selected. -
SQL QUERY How to write a sql query with a complex where clause.
I would like to get a list of all my invoices from the past year plus any open invoices that are more than a year old.
I don't want any overlapping rows.
Debra has a questionDebra,
Sorry but you have posted to a forum that deals exclusively with questions/issues about customizing and programming Microsoft Project, a planning and scheduling application. I suggest you delete this post and find a more appropriate forum.
John -
How to execute this SQL Query in ABAP Program.
Hi,
I have a string which is the SQL Query.
How to execute this sql Query (SQL_STR) in ABAP Program.
Code:-
DATA: SQL_STR type string.
SQL_STR = 'select * from spfli.'.
Thanks in Advance,
VinayHi Vinay
Here is a sample to dynamically generate a subroutine-pool having your SQL and calling it.
REPORT dynamic_sql_example .
DATA: BEGIN OF gt_itab OCCURS 1 ,
line(80) TYPE c ,
END OF gt_itab .
DATA gt_restab TYPE .... .
DATA gv_name(30) TYPE c .
DATA gv_err(120) TYPE c .
START-OF-SELECTION .
gt_itab-line = 'REPORT generated_sql .' .
APPEND gt_itab .
gt_itab-line = 'FORM exec_sql CHANGING et_table . ' .
APPEND gt_itab .
gt_itab-line = SQL_STR .
APPEND gt_itab .
gt_itab-line = 'ENDFORM.' .
APPEND gt_itab .
GENERATE SUBROUTINE POOL gt_itab NAME gv_name MESSAGE gv_err .
PERFORM exec_sql IN PROGRAM (gv_name) CHANGING gt_restab
IF FOUND .
WRITE:/ gv_err .
LOOP AT gt_result .
WRITE:/ .... .
ENDLOOP .
*--Serdar
Maybe you are looking for
-
Why do I need to pass params. to getConnection when using OracleDataSource?
Hi, I've been experimenting with Tomcat 5.5 and using Oracle proxy sessions. After many false starts, I finally have something working, but I have a question about some of the code. My setup: In <catalina_home>/conf/server.xml I have this section: <C
-
I7 in 15 inch or 17? for photography. . . .
So my problem is I am trying to decide which to order, a 15 or 17 inch in the i7. I have had a PowerBook G4 for about 4 years and need to upgrade as this is too slow with the larger files I now work with. I use Leica, which uses the SD card and my Ca
-
Loading data from flat file...
Hello, I am actually experiencing a problem where I cant load data from a flat file into a table. I have actually reverse engineered the flat file into ODI. But the thing is I don't know how to load the data that is reversed into a RDBMS table. Added
-
Problem in Transporting Function module
Hi, I have created a bapi(RFC). For testing I created several copies and Bapi Object and the last version got sucessful . but now I am getting problem in transportation, I have included the FM and Function group in the new request no but the include
-
I need to install JAVA CRYPTO TOOLKIT on XI 3.0. is the Plain J2SE Adapter engine a prerequiste for Java Crypto Toolkit?