How to write this SQL query
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
Similar Messages
-
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 -
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) -
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 -
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 code ?
for example below shows:
create table temp
order_type varchar2(30),
order_num number);
insert into temp values('apple',000001);
insert into temp values('banana',000002);
insert into temp values('chair',000003);
select *
from temp
where instr(order_type,decode(x,1,'a',2,'b',2,'c',order_type)) >0
if i let x equals 2 and i want to get b and c from above querying .
why above query could not get 'c' and only get 'b' if i give 2 to x ?
how to write above select clause ?
who can help me ?
thanks!Decode will return the first match;
SQL> select decode(2,1,'a',2,'b',2,'c')
from dual
D
b
1 row selected.This may help;
old: select *
from temp
where regexp_like(order_type, case to_number(&x)
when 1 then 'a'
when 2 then 'b|c'
end)
new: select *
from temp
where regexp_like(order_type, case to_number(2)
when 1 then 'a'
when 2 then 'b|c'
end)
ORDER_TYPE ORDER_NUM
banana 2
chair 3
2 rows selected. -
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 convert this SQL query to PL/SQL
I basically need to create an anonymous block that will display each student's first name, last name and the count of students who scored less on test 1 than the student.
So basically we need to find the count of students who have scored less than that particular student and we do it for all students in the table.
So for this particular query i designed my code in SQL
select g1.gr_fname, g1.gr_lname, count(*)
from grade g1, grade g2
where g1.gr_t1 > g2.gr_t1 and
g1.std_code = g2.std_code
group by g1.gr_fname, g1.gr_lname;
But i am unable to get the logic as to how to execute it in PL/SQL,I am missing something a minor detail to execute the same in PL/SQL
could someone please help me with the logic.
ThanksHi welcome to the forum try some thing below
SQL> DECLARE
2 CURSOR c1
3 IS
4 SELECT ename, sal, d.deptno
5 FROM scott.emp e, scott.dept d
6 WHERE e.deptno = d.deptno
7 GROUP BY ename, sal, d.deptno;
8 BEGIN
9 FOR c2 IN c1
10 LOOP
11 DBMS_OUTPUT.put_line ('name is ' || c2.ename);
12 END LOOP;
13 END;
14 /
name is CLARK
name is KING
name is JONES
name is MARTIN
name is FORD
name is SCOTT
name is ALLEN
name is TURNER
name is WARD
name is MILLER
name is ADAMS
name is BLAKE
name is JAMES
name is SMITH
PL/SQL procedure successfully completed.This is just to demonstrate the use of PL/SQL block -
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 -
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 use this sql query in oracle?
Hi all,
i am using one sql query that is
SELECT @ToDate = '2012-10-03 00:00:00.000'
select @BetweenDate = DATEADD(MM,-1,@ToDate)
select @FromDate = DATEADD(m,DATEDIFF(m,0,@BetweenDate),0)
SELECT @ToDate = DATEADD(month, ((YEAR(@BetweenDate) - 1900) * 12) + MONTH(@BetweenDate), -1)
so @todate value is = '2012-10-03 00:00:00.000'
so in @betweendate value will come 1 month before like '2012-09-03 00:00:00.000'
again in @fromdate value will come like that '2012-09-01 00:00:00.000' means first date of @betweendate
and again @todate value will come like that '2012-09-30 00:00:00.000' means last date of @betweendate
it's happening in sql and i have to use same logic in oracle also.
how to use it??
thanksdeclare
todate date:= to_date('2012-10-03 00:00:00','yyyy-mm-dd hh:mi:ss');
betwendate date := add_months(todate,-1);
for datediff / additions you can direct subtract/add two different date variables
like
datediff = betweendate -todate
dateadd := todate+1; -
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 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 CTEFull 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] -
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.
Maybe you are looking for
-
No backup possible, even after a clean re-install
I - NEED - HELP!!! This is what happens before I encountered my problems with backing up my hard drive: I'm using a MacBook Pro 17" Unibody. The hard drive was partitioned into two partitions. The first one was the bootcamp partition, 50 GBytes in si
-
HT1695 Wifi issues linked to updates
I never had any issues with wifi until i updated to ios6 and ios6.0.1 and i can connect to any internet other than home. Iv done everything resotred my ipod and the router the router is up to date and so is my ipod, iv reset the network connections,
-
Documents Created Seen in more than one report globally
Hi Experts, I would like to know whether the documents can be created globally? such that they can be seen in more than one queries in common. For better understanding my requirement is to know whether the documents can be created in such a way t
-
When i try to log in to email, all fields clear and wont log in
I am trying to log into my email with charter.net and whenever i enter all correct info and click on the log in button, all my fields just clear out and no error message even pops up
-
Firefox does not load pages at all..
Hello, I upgraded to FireFox 7, and since upgrading I cannot load pages at all. I closed FF to update, then when I tried to restore my session, none of the pages would load; they're stuck in a never ending "connecting" state. I've tried disabling all