Help! SQL Qs2.
thx to thomas.kellerer who help mi juz now.
now i have another Qs regarding sql.
How to extract the LAST row of records in a Table?? I need to do this because all the attributes in the table be similar.
The table may look like this:
TABLE Test
OrderID | acountID | name
1 88 lee
2 88 lee
3 77 mike
4 77 mike
Only the orderId is unique but is auto-generated, but i only want the most recent record...which is the last row. So how can i get the last row of records?
select orderId from test where accountID = ? AND name = ?
This Sql doesn't seem to help.
Not a SQL forum but how about something like:set rowcount 10
select * from Test order by OrderId descThis works for SQL Server 2000; for Oracle, it's something likeselect * from Test where rownum < 10 order by OrderId descThere's also a select top 10 * from Test order by OrderId descI think this last one is a SQL Server special and is frowned upon by DB people (I know not why) but hopefully one of these might help you.
All the best...
CB.
Similar Messages
-
很全的help.sql 安装Oracle的sqlplus帮助系统
在linux系统下的时候,我们可以通过man命令,获得系统里对某个命令的usage的解释。
在sqlplus里我们也可以通过help和?命令。
sqlplus的帮助主题对应的是数据库里的一张表(system.help)。
在$ORACLE_HOME/sqlplus/admin/help/目录下的helpus.sql包含了这个表的帮助主题
不过oracle自带的help和?的解释太少了
在网上找了很久终于找到一个很全的help.sql叻
下载文中附件,用system登录,因为这个是建立在system的schema里的help表里的。
直接执行脚本就可以了。比如我把这个sql保存到$ORACLE_HOME\sqlplus\admin\help里,
大家在这里可以看到有
helpbld.sql
helpdrop.sql
helpus.sql
hlpbld.sql
这四个文件,这就是oracle自带的help脚本。可以执行
helpbld.sql来安装oracle默认的help, 这里会提示你输入两个参数,看了这个源文件。
两个参数一个是当前路径,一个是helpus.sql, 还是用system来执行,执行完就安装了help,
就可以使用我上面的那些方式。这个是默认会安装的。
要安装我这个最新的help文件,只需要执行就可以了
SQL>conn system/systempwd;
SQL>@?/sqlplus/admin/help/helpbld.sql
输入 1 的值: F:\developer\oracle\product\10.2.0\db_1\sqlplus\admin\help
输入 2 的值: F:\developer\oracle\product\10.2.0\db_1\sqlplus\admin\help\help.sql
这里就会执行了,执行是有一些和默认的有冲突,可以忽略这些错误。
成功以后,我们执行一下
SQL> select count(*) from system.help ;
COUNT(*)
5085
呵呵呵一下多了好多条了哟
SQL> help create database;
引用:
CREATE DATABASE
Use this command to create a database, making it available for
general use, with the following options:
* to establish a maximum number of instances, data files, redo
log files groups, or redo log file members
* to specify names and sizes of data files and redo log files
* to choose a mode of use for the redo log
* to specify the national and database character sets
Warning: This command prepares a database for initial use and erases
any data currently in the specified files. Only use this command
when you understand its ramifications.
.......这里还要好多有关create table的帮助信息,我就不写了。
有了这个帮助系统,要查一个命令的详解,正是太方便叻。
help.sql文件【 下载 】 -
Need help-SQL with result format suppressing duplicate values
I am trying to write a SQL which would select data from the below tables(in reality i have many other tables also) but I wanted to know how do i get the data in the format given below.
The scenario is :-A training_plan can N no. of OBJECTIVES and EACH objective has N no.of activities
Insert into TEST_TRAINING_PLAN
(TPLAN_ID, TPLAN_NAME, TPLAN_DESC, T_PERSON_ID
Values
('111', 'test_name', 'test_name_desc', '****')
Objectives table:-
Insert into TEST_TRAINING_OBJECTIVE
(T_OBJECTIVE_ID, T_OBJECTIVE_NAME,T_owner)
Values
('10', 'objective1', '1862188559')
Objective and Training Plan relationship table where TPLAN_ID is the foreign key.
Insert into TEST_TP_OBJECTIVE
(TPLAN_TOBJ_ID, TPLAN_ID, T_OBJECTIVE_ID,
REQUIRED_CREDITS)
Values
('1', '111', '10',5)
Objective and Activity relationship table where T_OBJECTIVE_ID is the foreign key from the TEST_TRAINING_OBJECTIVE table.
Insert into TEST_TRAIN_OBJ_ACTIVITY
(TOBJ_TRAIN_ACTIVITY, T_OBJECTIVE_ID, ACTIVITY_ID, IS_REQUIRED, STATUS,
ACTIVITY_TYPE, ITEM_ORDER, IS_PREFERRED)
Values
('1000', '10', 'selfstudy event', SS1, NULL,
'Event', 0, 0);
Insert into TEST_TRAIN_OBJ_ACTIVITY
(TOBJ_TRAIN_ACTIVITY, T_OBJECTIVE_ID, ACTIVITY_ID, IS_REQUIRED, STATUS,
ACTIVITY_TYPE, ITEM_ORDER, IS_PREFERRED)
Values
('1001', '10', 'SQLcourse', 1, NULL,
'Course', 1, 0);
Insert into TEST_TRAIN_OBJ_ACTIVITY
(TOBJ_TRAIN_ACTIVITY, T_OBJECTIVE_ID, ACTIVITY_ID, IS_REQUIRED, STATUS,
ACTIVITY_TYPE, ITEM_ORDER, IS_PREFERRED)
Values
('1002', '10', 'testSQL', 1, NULL,
'test', 2, 0);
COMMIT;
firstname emplid Tplan name Number of activities/credits completed(for TP) Objective Name Number of required activities/Credits (for objective) Number of activities/credits completed(for objective) activity name activity completion status
U1 U1 TP1 5
OBJ1 4 3 C1 PASSED
C2 PASSED
C3 WAIVED
T1 ENROLLED
T2 ENROLLED
OBJ2 3 2
S1 ENROLLED
S2 PASSED
T3 WAIVED
U1 U1 TP2 C4 INPROGRESS
50 OBJ11 50 30 C11 PASSED
**The second row where we have another training_plan record and accordingly all objectivesand their objective.**similarly ,i need to display many Training_plan records in such tabular format.Please help with the SQL query to select and display data in the above format
If you want to suppress duplicate values in some of your results columns
I am using toad 9.1 using Oracle 10g version 2Hi,
You can use the BREAK command to suppress duplicate values.
http://download.oracle.com/docs/cd/B19306_01/server.102/b14357/ch12009.htm#SQPUG030
(scroll down for an example)
It's a 'SQL*Plus-ism', not sure if TOAD's capable to handle it.
Simple example:
HR%xe> break on department_name
HR%xe> select l.department_name
2 , e.last_name
3 , e.first_name
4 from departments l
5 , employees e
6 where e.department_id = l.department_id;
DEPARTMENT_NAME LAST_NAME FIRST_NAME
Executive King Steven
Kochhar Neena
De Haan Lex
IT Hunold Alexander
Ernst Bruce
Austin David
Pataballa Valli
Lorentz Diana
Finance Greenberg Nancy
Faviet Daniel
Chen John
Sciarra Ismael
Urman Jose Manuel
Popp Luis
Purchasing Raphaely Den
Khoo Alexander
Baida Shelli
Tobias Sigal
Himuro Guy
Colmenares Karen
Shipping Weiss Matthew
Fripp Adam
Kaufling Payam
Vollman Shanta
Mourgos Kevin
Nayer Julia
Mikkilineni Irene
Landry James
Public Relations Baer Hermann
Accounting Higgins Shelley
Gietz William
106 rijen zijn geselecteerd. -
Hi,
I have two functions.But some codes are the same so I want to merge in one function.
My code is:
function get_column_name (p_table_name in varchar2) return varchar2 is
l_var varchar2(100) := null;
l_str varchar2(2000) := null;
i int := 1;
begin
for l_rec in (select COLUMN_NAME item_name,COLUMN_NAME display_name from all_tab_cols
where table_name = p_table_name
and column_name not in (select a.item_name
from item_t a
where a.table_name = p_table_name)
union all
(select item_name,display_name
from item_t
where table_name = p_table_name)
loop
if (instr(upper(l_rec.item_name), 'DATE') > 0) or (instr(upper(l_rec.item_name), 'TIME') > 0) then
l_var := 'to_char(' || l_rec.item_name || ', ''yyyymmdd hh24mmss'') '||l_rec.display_name;
elsif (l_rec.item_name != l_rec.display_name) then
l_var := l_rec.item_name||' '||l_rec.display_name;
else
l_var := l_rec.item_name;
end if;
if ( i = 1 ) then
l_str := l_var;
else
l_str := l_str || ',' || l_var;
end if;
i := i + 1;
end loop;
if (l_str is null) then l_str := '*';
end if;
return l_str;
end;
function get_column_name (p_table_name in varchar2,p_column_name_list in item_list) return varchar2 is
l_var varchar2(100) := null;
l_str varchar2(2000) := null;
i int := 1;
begin
for l_rec in (select COLUMN_NAME item_name,COLUMN_NAME display_name from all_tab_cols
where table_name = p_table_name
and column_name not in (select a.item_name
from cmn_lookup_item_t a
where a.table_name = p_table_name)
union all
(select item_name,display_name
from cmn_lookup_item_t
where table_name = p_table_name
and display_name in (select value from table(cast(p_column_name_list as item_list ))))
loop
if (instr(upper(l_rec.item_name), 'DATE') > 0) or (instr(upper(l_rec.item_name), 'TIME') > 0) then
l_var := 'to_char(' || l_rec.item_name || ', ''yyyymmdd hh24mmss'') '||l_rec.display_name;
if (l_rec.item_name != l_rec.display_name) then
l_var := l_rec.item_name||' '||l_rec.display_name;
else
l_var := l_rec.item_name;
end if;
if ( i = 1 ) then
l_str := l_var;
else
l_str := l_str || ',' || l_var;
end if;
i := i + 1;
end loop;
if (l_str is null) then l_str := '*';
end if;
return l_str;
end; The code start 'loop' is the same just different at 'l_rec' part.How can i merge it?
Thanks for your help!
JingSimple example:
SQL> create or replace type my_type is table of varchar2(20)
2 /
Type created.
SQL> create or replace package my_pkg
2 is
3 coll my_type := my_type('SALESMAN');
4 end;
5 /
Package created.
SQL> create or replace procedure my_prc
2 (
3 deptno number,
4 job_list my_type default null
5 )
6 is
7 begin
8 for v in (select ename from emp where deptno = my_prc.deptno
9 and (job in (select column_value from table(cast(job_list as my_type)))
10 or job_list is null)) loop
11 dbms_output.put_line(v.ename);
12 end loop;
13 end;
14 /
Procedure created.
SQL> exec my_prc(30);
ALLEN
WARD
MARTIN
BLAKE
TURNER
JAMES
PL/SQL procedure successfully completed.
SQL> exec my_prc(30,my_pkg.coll);
ALLEN
WARD
MARTIN
TURNER
PL/SQL procedure successfully completed.
SQL> select ename, job from emp where deptno = 30;
ENAME JOB
ALLEN SALESMAN
WARD SALESMAN
MARTIN SALESMAN
BLAKE MANAGER
TURNER SALESMAN
JAMES CLERK
6 rows selected.Rgds. -
Urgent Help - SQL Statement..
hai everybody,
i need ur help in writing a SQL statement..
i have 2 tables say
CATEGORY
cat_id cat_name
B001 IT
B002 Accounts
B003 Clerk
SUB CATEGORY
sub_cat_id sub_cat_name cat_id
S001 programming B001
S002 Admin B001,B002
S003 HR B001,B002,B003
i want to display one as liek ths
sub_cat_name cat_name
Programming IT
admin IT,Accounts
HR IT,Accounts,Clerk
how to write a qry for this..pl help..
thanx in advance
regards
koelThis is just a natural join between two tables.
The query can be like this:
select b.sub_cat_name, a.cat_name
from category a, sub_category b
where a.cat_id = b.cat_id
Pl. let me know whether this solves your problem. -
Please Help - SQL Report long column value required in a separate cell
Hi.
I need to create a SQL report with the structure like below:
Country State City Vertical Business Details (detail desc)
US MA Quincy Healthcare
This is a detail desc value that needs to displayed in a different cell.
This is a detail desc value that needs to displayed in a different cell.
This is a detail desc value that needs to displayed in a different cell.
This is a detail desc value that needs to displayed in a different cell.
US MA Braintree IT
This is a detail desc value that needs to displayed in a different cell.
This is a detail desc value that needs to displayed in a different cell.
This is a detail desc value that needs to displayed in a different cell.
I came through a solution where you can hide/display the long column value in a different cell. But my requirement is that it should be displayed when the page opens and user don;t want to click on a button to see the value. This is mainly for their presentations and printing. so its very annoying for them to click on so many buttons to see the detail desc value for every record. I am new to Java script, Please helpI'm not sure I understand your requirements--are you showing us 2 lines of data, 7 lines, or 9? Do you want the long detail description on the same row, or underneath it?
I'm going to go on the assumption that you're showing us two rows, and that the long descriptions in this example happen to be 3-4 lines long, and that you want the long descriptions underneath the details. In which case, I suggest using "named column" templates. They're a lot easier to use than they appear when you first look at them, so bear with me.
Under "Shared Components", select "Templates", and then click on the yellow Create> button. You're creating a report template, from scratch. On the final page of the wizard, select "Named Column (row template)" for the template type. This will create a rather generic (and useless) template, which you'll have to edit; I don't know why they chose to not send you straight into the editor. When you edit it, you'll see that the only field with a value in it is "Row Template 1", and it's set to:
<tr><td>#1#</td><td>#2#</td><td>#3#</td><td>#4#</td><td>#5#</td></tr>For meeting your requirements with basic functionality, change it to something along the lines of:
<tr><td>#COUNTRY#</td><td>#STATE#</td><td>#CITY#</td><td>#VERT#</td></tr>
<tr><td colspan="4">#DETAILS#</td></tr>Then you'll probably want to put something under Column Heading Template, like:
<tr><td>Country</td><td>State</td><td>City</td><td>Vertical Business</td></tr>
<tr><td colspan="4">Details</td></tr>Apply whatever CSS styles you want to it, of course.
Using the template is straightforward: if your report, chose the template, and make sure your SQL returns values using the column names you specified in your template. Otherwise, you'll see literal "#COUNTRY#" text in your report.
You can get fancy with these, of course, such as applying different styles to alternating rows, but I'll leave this as good enough to get you started (I hope).
-David -
HELP - SQL Server Express Install Problems
The SQL Server Express completed without error. However, when I tried to connect to the SQLEXPRESS instance I received one of those wonderful MS errors, "Specified file not found". WHAT FILE? (After all these years MS still can't figure out how
to give an error msg. that provides some hint of what's wrong.) Going on, I started the install console and selected the REPAIR option. (It didn't ask what the problem was, it just ran.) It did ask what instance needed repair. I told
it SQLSERVER. It proceeded to repairing it. My first hint that their repair function worked as well as their error handling was when I got the: That share name has already been used (or something like that) error (notice, MS didn't tell me what
share name, or what aspect of the db they were talking about). After pressing OK, the REPAIR function proceeded to run to completion. When I reviewed the REPAIR report I found that three db processes all had the same SHARE NAME ALREADY USED error.
Actually, I thought that it was no big deal. If this was a real REPAIR, it shouldn't matter that the name was already used because everything else should be the same. (I know I'm nigh eve about the
Intricacies of SQL server.) After repairing my installation, I brought up the SQL Server Management Console again. This time, it did not display SQLEXPRESS in the Connect field. I selected the drop down list arrow to see if it was
listed and the list was blank so I entered SQLEXPRESS in the connect field and clicked on the CONNECT button. I got a NETWORK PATH NOT FOUND error. So, before I really mess things up, I thought I should ask if anyone knows what I should do
next. (As an aside, I've pressed the MS Error Message HELP button numerous times abut various errors I've received over the years. Not only are MS error messages useless, their Help Page has never ONCE been able to provide any information
about the encountered error. MS should spend some time and develop some truly helpful error messages as "File not found" and unknown error code 837289 are absolutely useless and especially since their HELP PAGE is never able to provide any
information either. I do wonder how I can get Unknown Error codes from people who wrote the code that raises the error. Don't they document anything?)I did read the requirements and made sure I met them all. The install package I used was: SQLEXPRADV_x64_ENU.exe. You're correct. I'm not familiar with SQL Server.
I downloaded SQL Server Express and Visual Studio Express to learn and explore because I wanted to learn about the new technology.
After leaving my message, I did some more studying and playing with the system. I managed to figure out that I had to turn on the data base service before I could connect with it. I'm sorry, I don't understand how Microsoft could install a data
base system without turning on its services. Why would I want to install something and NOT use it? The default should be ON and the setup manager should provide a choice to set it to OFF on the configuration page.
My experience is rather dated. I had to retire due to a disability in 2005. I couldn't control my arms and hands. The doctor recently tried a medication again that I had had a severe negative reaction to. He first administered steroids
and started me on a small dose and titrated it up as I was able to handle it. Now I have some days where I have pretty good control — I can print a little but can't write well and other days where I can't print, write, or feed myself.
I have performed many functions. I have been an analyst, a programmer, a data base designer, and a college professor at three different colleges. I've done extensive work in process automation and have even automated the management functions
for a data base system that was used to schedule every aspect of all the aircraft, ranges, and weapons development processes on Eglin AFB. I also wrote major pieces of the code used by the system and trouble shot and corrected functions written by other
programmers. The system supported over 300 users a day on two bases. Unfortunately it was developed in Fortran on a VAX and with VB6 and MS Access using VBA, Queries, Tables and Forms on networked PCs.
I plan to do a lot of reading. I'll also be looking at the Microsoft sites for a sample DB and lessons to go with it. I am a little frustrated with how information is organized on the web. The other night I needed to find some information
about something from Microsoft. It took me almost two hours to ask my question in such a way that MS was able to provide what I wanted. I kept asking essentially the same thing, but I had to use the exact phrase MS used on the page. I know
MS is big and they support multiple generations of each product. They have an almost impossible task. I just have to find the various product entry pages.
Thanks for offering your help. -
HELP: SQL*LOADER AND Ref Column
Hallo,
I have already posted and I really need help and don't come further with this
I have the following problem. I have 2 tables which I created the following way:
CREATE TYPE gemark_schluessel_t AS OBJECT(
gemark_id NUMBER(8),
gemark_schl NUMBER(4),
gemark_name VARCHAR2(45)
CREATE TABLE gemark_schluessel_tab OF gemark_schluessel_t(
constraint pk_gemark PRIMARY KEY(gemark_id)
CREATE TYPE flurstueck_t AS OBJECT(
flst_id NUMBER(8),
flst_nr_zaehler NUMBER(4),
flst_nr_nenner NUMBER(4),
zusatz VARCHAR2(2),
flur_nr NUMBER(2),
gemark_schluessel REF gemark_schluessel_t,
flaeche SDO_GEOMETRY
CREATE TABLE flurstuecke_tab OF flurstueck_t(
constraint pk_flst PRIMARY KEY(flst_id),
constraint uq_flst UNIQUE(flst_nr_zaehler,flst_nr_nenner,zusatz,flur_nr),
flst_nr_zaehler NOT NULL,
flur_nr NOT NULL,
gemark_schluessel REFERENCES gemark_schluessel_tab
Now I have data in the gemark_schluessel_tab which looks like this (a sample):
1 101 Borna
2 102 Draisdorf
Now I wanna load data in my flurstuecke_tab with SQL*Loader and there I have problems with my ref column gemark_schluessel.
One data record looks like this in my file (it is without geometry)
1|97|7||1|1|
If I wanna load my data record, it does not work. The reference (the system generated OID) should be taken from gemark_schluessel_tab.
LOAD DATA
INFILE *
TRUNCATE
CONTINUEIF NEXT(1:1) = '#'
INTO TABLE FLURSTUECKE_TAB
FIELDS TERMINATED BY '|'
TRAILING NULLCOLS (
flst_id,
flst_nr_zaehler,
flst_nr_nenner,
zusatz,
flur_nr,
gemark_schluessel REF(CONSTANT 'GEMARK_SCHLUESSEL_TAB',GEMARK_ID),
gemark_id FILLER
BEGINDATA
1|97|7||1|1|
Is there a error I made?
Thanks in advance
Tigmultiple duplicate threads:
to call an oracle procedure and sql loader in an unix script
Re: Can some one help he sql loader issue. -
Awhile back I found a great site that had a list of helpful hints of basic SQL commands and examples. I forgot it and wondered if anyone knows of some other helpful sites that have basic SQL code to use for examples
Hi Ryan,
Am not quite sure which site you really had in mind. But an alternative would be to try the publication sites such as Osborne and Oreilly, as they distribute the code discussed in their books. So you could pick up some appropriate book title to get the necessary sample free codes.
Could try : http://osborne.com/oracle/
Hope this does help.
Ranjith. -
Pls. help, SQL script page problem
Hi,
Im using the Hands On Oracle Database 10g Express Edition for Linux. Im in chap06 already p. 218. I just uploaded the SYSMGMT1 script. After that I Clicked the script's icon but I cannot see any SQL DDL commands inside. Nothing happened. It said in the book that I supposed to see and browse the SQL DDL commands that make up the script. I tried to click RUN, nothing happened either. Is there some kind of a bug in my System? Pls. help me because I cannot continue this chapter's exercise if I cannot solve this first problem that I encountered here in chap06. Any help from the guys outhere is really greatly appreciated. Thank you.
respectfully waiting,
LenHi, did you ever get a solution to this because I am having exact same problem - I cannot see the scripts if I upload them nor can I type them in from scratch as the area for seeing/editting the script doesn't seem to be accessible.
-
Help: SQL to select closest points within groups of records grouped by time
Hi,
I need help to find an SQL for efficient solution for the following problem:
- I have 20 buses circling on one bus route and their locations are reported every 10 seconds and recorded into a spatial table “bus_location” with “bus_loc” as SDO_GEOMETRY type.
- Each bus location record there has a msg_datetime column with the time when the location was recorded.
- Buses circle the bus route 8-12 times, from A to B, then from B back to A, then new loop from A to B, and so on.
- I have 3 timing points in spatial table “timing_point” with “tp_loc” as SDO_GEOMETRY type.
- A bus will pass each timing point 8-12 times in one direction and 8-12 times in the other direction, while making loops on the bus route.
My task is: for each timing point, for each bus, for each trip direction (A-B or B-A), find the closest bus location to that timing point.
Example:
Bus...*TimingPoint*......*Time*.....*Distance*
...........................................*between*
...........................................*bus and TP*
12......A................14:01:00......250 m
12......A................14:01:10......150 m
12......A................14:01:20......12 m <== This is the record closest to the TP for this pass
12......A................14:01:30......48 m
12......A................14:01:40......100 m
12......A................14:01:50......248 m
12......A................14:29:40......122 m
12......A................14:29:50......72 m
12......A................14:30:00......9 m <== This is the record closest to the TP for this pass
12......A................14:30:10......10 m
12......A................14:30:20......12 m
I tried to use SDO_NN and I can get closest bus locations, but how to find the closest bus location for each pass? Or how to identify a groups of bus locations which are together within 2-3 minutes and to find closest record for each of these groups of locations?
Thank you very much for any help.
Milan
Edited by: mburazor on 9-Feb-2012 2:41 PMMilan,
Yes, the problem is one of analytics not spatial. Here is another go that should be independent of year/month/date/hour/minute
as it does all its math based on an absolute number of minutes since 1970. I round to 5 minutes but you could round/trunc to any
particular interval (5 minutes, 10 minutes, 15 minutes etc)
Note that I have created extra records in the same table that I built. (Tip: good idea to provide a sample dataset to the forum when
asking difficult SQL questions like this.)
drop table buslocns;
create table buslocns(
busno number,
timingpt varchar2(1),
pttime timestamp,
distance number)
insert into buslocns values (12,'A',to_timestamp('2012/02/10 14:01:00','YYYY/MM/DD HH24:MI:SS'),250);
insert into buslocns values (12,'A',to_timestamp('2012/02/10 14:01:10','YYYY/MM/DD HH24:MI:SS'),150);
insert into buslocns values (12,'A',to_timestamp('2012/02/10 14:01:20','YYYY/MM/DD HH24:MI:SS'),12);
insert into buslocns values (12,'A',to_timestamp('2012/02/10 14:01:30','YYYY/MM/DD HH24:MI:SS'),48);
insert into buslocns values (12,'A',to_timestamp('2012/02/10 14:01:40','YYYY/MM/DD HH24:MI:SS'),100);
insert into buslocns values (12,'A',to_timestamp('2012/02/10 14:01:50','YYYY/MM/DD HH24:MI:SS'),248);
insert into buslocns values (12,'A',to_timestamp('2012/02/10 14:29:40','YYYY/MM/DD HH24:MI:SS'),122);
insert into buslocns values (12,'A',to_timestamp('2012/02/10 14:29:50','YYYY/MM/DD HH24:MI:SS'),72);
insert into buslocns values (12,'A',to_timestamp('2012/02/10 14:30:00','YYYY/MM/DD HH24:MI:SS'),9);
insert into buslocns values (12,'A',to_timestamp('2012/02/10 14:30:10','YYYY/MM/DD HH24:MI:SS'),10);
insert into buslocns values (12,'A',to_timestamp('2012/02/10 14:30:20','YYYY/MM/DD HH24:MI:SS'),12);
insert into buslocns values (12,'A',to_timestamp('2012/02/10 14:59:40','YYYY/MM/DD HH24:MI:SS'),53);
insert into buslocns values (12,'A',to_timestamp('2012/02/10 14:59:50','YYYY/MM/DD HH24:MI:SS'),28);
insert into buslocns values (12,'A',to_timestamp('2012/02/10 15:00:00','YYYY/MM/DD HH24:MI:SS'),12);
insert into buslocns values (12,'A',to_timestamp('2012/02/10 15:00:10','YYYY/MM/DD HH24:MI:SS'),73);
insert into buslocns values (12,'A',to_timestamp('2012/02/10 14:44:40','YYYY/MM/DD HH24:MI:SS'),53);
insert into buslocns values (12,'A',to_timestamp('2012/02/10 14:44:50','YYYY/MM/DD HH24:MI:SS'),28);
insert into buslocns values (12,'A',to_timestamp('2012/02/10 15:45:00','YYYY/MM/DD HH24:MI:SS'),12);
insert into buslocns values (12,'A',to_timestamp('2012/02/10 15:45:10','YYYY/MM/DD HH24:MI:SS'),73);
commit;
with tensOfMinutes as (
select row_number() over (order by busno,timingpt, pttime) as rid,
busno,
timingpt,
pttime,
round(((cast(pttime as date) - cast('01-JAN-1970' as date)) * 1440) / 5) * 5 as mins,
distance
from BUSLOCNS
select busno,timingpt,to_char(to_date('01-JAN-1970','DD-MON-YYYY') + ( mins / 1440 ),'DD-MON-YYYY HH24:MI:SS') as pttime,minDist
from (select busno,timingpt,mins,min(distance) as minDist
from tensOfMinutes a
group by a.busno, a.timingpt, a.mins
order by 1, 2, 3 ) ;
-- Result
BUSNO TIMINGPT PTTIME MINDIST
12 A 10-FEB-2012 14:00:00 12
12 A 10-FEB-2012 14:30:00 9
12 A 10-FEB-2012 14:45:00 28
12 A 10-FEB-2012 15:00:00 12
12 A 10-FEB-2012 15:45:00 12regards
Simon -
Hi everyone:
Here i have a table:
create table cap_binding (
test_ser_id NUMBER(10) not null,
test_cap_id NUMBER(10) not null,
cap_binding_id NUMBER(10) not null,
constraint PK_CAP_BINDING primary key (cap_binding_id)
insert into cap_binding values(64,21,1);
insert into cap_binding values(64,1,2);
insert into cap_binding values(65,1,3);
now, i want to find out the test_ser_id where the corresponding test_cap_id is 21 AND 1 , and in the given
data, the result should be the first two records.
initially, i write: select y.TEST_SER_ID from cap_binding y where y.test_cap_id in (1,21), but the in operator performs OR logic and i get three records.
I cannot figure out how to write the sql. Could anyone help me?
Thanks.This will work if you have a unique constraint on test_ser_id, test_cap_id:
with t as (
select 1 col1 from dual UNION ALL
select 21 col1 from dual
select * from (
select test_ser_id,
test_cap_id,
cap_binding_id,
COUNT(*) OVER (PARTITION BY test_ser_id) cnt
from cap_binding)
where cnt = (SELECT DISTINCT COUNT(*) FROM t);
TEST_SER_ID TEST_CAP_ID CAP_BINDING_ID CNT
64 21 1 2
64 1 2 2
2 rows selectedI used a table using a with clause to store the values we are looking for (1, 21), but you could use a pipelined function or a variable as well. -
Help: SQL list all duplicate records
Given table B with employer_id, ssn, period and employee_name, list all records with duplicate ssn for a given period and employer_id.
I used:
select employer_id, ssn, employee_name, count(ssn) from B
group by employer_id, ssn
where period='xxx' and count(ssn)>1
got error:
ORA-00933: SQL command not properly ended
checked sometime and still can not figure it out, any help will be greatly appreciated.select employer_id, ssn, employee_name, count(ssn) from B
where period='xxx'
group by employer_id, ssn,employee_name having count(ssn)>1
Regards
Helio Dias
http://heliodias.com -
SELECT MATNR EBELP EBELN MENGE
FROM EKBE
INTO TABLE I_EKBE
FOR ALL ENTRIES IN I_EKKN_EKPO
WHERE EBELN EQ I_EKKN_EKPO-EBELN
AND MATNR EQ I_EKKN_EKPO-MATNR
AND VGABE EQ '1'
AND BEWTP EQ 'E'
AND SHKZG EQ 'S'.
when i am query in database tables i am getting 4 records
with same condtion , but with sql query i getting 2 records .
what is wrong with above code .
in ekkn_ekpo there are 2 records but in ekbe table i have 4 records for that certia ( which i should get).
it picking up unique records ( first one ).
how get 4 records all?
Thanks,
sridharHi Sridhar,
The problem is due to the FOR ALL ENTRIES usage. You have used the FOR ALL ENTRIES for EBELN and MATNR. As such, the system tries to fetch for each row, the corresponding values from the table EKBE. But when you use more than 1 field for selection, the logic breaks and hence you should try to use RANGES to read the data correctly.
For your example, you would have to gather the MATNR from I_EKKN_EKPO internal table in a RANGES variable and then use it in the SELECT statement.
i.e.
RANGES: R_MAT FOR EKBE-MATNR.
R_MAT-OPTION = 'EQ'.
R_MAT-SIGN = 'I'.
LOOP AT I_EKKN_EKPO.
AT NEW MATNR.
R_MAT-LOW = I_EKKN_EKPO-MATNR.
APPEND R_MAT.
ENDAT.
ENDLOOP.
SELECT MATNR EBELP EBELN MENGE
FROM EKBE
INTO TABLE I_EKBE
FOR ALL ENTRIES IN I_EKKN_EKPO
WHERE EBELN EQ I_EKKN_EKPO-EBELN
AND MATNR IN R_MAT
AND VGABE EQ '1'
AND BEWTP EQ 'E'
AND SHKZG EQ 'S'.
But because you are looping thru the values of the I_EKKN_EKPO table, you might as well try the code below...
LOOP AT I_EKKN_EKPO.
SELECT MATNR EBELP EBELN MENGE
FROM EKBE
APPENDING INTO TABLE I_EKBE
WHERE EBELN EQ I_EKKN_EKPO-EBELN
AND MATNR EQ I_EKKN_EKPO-MATNR
AND VGABE EQ '1'
AND BEWTP EQ 'E'
AND SHKZG EQ 'S'.
ENDLOOP. " I_EKKN_EKPO.
Personally, I would advise you to go with the option 1 as it will work faster. *** SELECTs within LOOP generally work slower when the iterations increase.
Hope this helps.
Chaps. -
URGENT HELP: SQL ordering
Hi there
I have a set of records that I want to order using SQL. I want to sort them ascendingly by a numeric field. The trouble is that I want them ascending excluding the fields equalling zero. The fields with a value of zero should be listed last.
Is there any way to achieve this?
Hope someone can help me soon. It is incredibly urgent!!
ComlinkHi there
I have a set of records that I want to order using
SQL. I want to sort them ascendingly by a numeric
field. The trouble is that I want them ascending
excluding the fields equalling zero. The fields with
a value of zero should be listed last.
Is there any way to achieve this?This is probably a hack, but I can't figure out the subselect.
SELECT field1, field2 FROM table ORDER BY field1 WHERE field1 != 0;
SELECT field1, field2 FROM table WHERE field1 = 0;
Maybe you are looking for
-
Application stuck under menu toolbar
An application I'm running (Filezilla FTP client) is stuck under the mac menu toolbar. I can't grab the toolbar of the application to move it or access what I need to access. I've researched this issue and other people have had the same problem, but
-
I've just recently signed up for an iPhone 3gs I've had it for about a week now everything was working fine but now the youtube app refuses to play any video. Comes with with a message stating "video format not supported" the annoying thing, is that
-
Since device-mapper last update, dmsetup moved from /sbin to /usr/sbin Now, mkinitcpio fails with this message: [2013-02-12 17:23] ==> Starting build: 3.7.7-1-ARCH [2013-02-12 17:23] -> Running build hook: [base] [2013-02-12 17:23] -> Running build h
-
BI 10g multiple installation on same windows machine
Hi All, I have a requirement where in I want to install OBIEE 10g twice on the same windows server. Can we achieve this by installing it the second time as another OS User? What are the steps that we need to follow in this scenario? Most importantly,
-
VA01 - Sales Order - Cannot select Material relevant to Customer
Hi Gurus, I tried to create a sales order VA01. I have put a SP and when I try to select his matching material, the system cannot find it when pressing F4 into the item field. However, both customer and material have been created for: - Same Sales Ar