Tricky SQL query... how to get all data in a single query?
create table employee_definition (def_id number, def_name varchar(50));
insert into employee_definition values (100, 'EMAIL');
insert into employee_definition values (200, 'MOBILE_PHONE');
insert into employee_definition values (300, 'HOME_PHONE');
SQL> select * from employee_definition;
DEF_ID DEF_NAME
100 EMAIL
200 MOBILE_PHONE
300 HOME_PHONE
create table employee_data (def_id number, def_value varchar(20), emp_id number);
insert into employee_data values (100, '[email protected]', 123);
insert into employee_data values (200, '01232222', 123);
insert into employee_data values (300, '5555', 123);
insert into employee_data values (100, '[email protected]', 666);
insert into employee_data values (200, '888', 666);
insert into employee_data values (300, '999', 666);
insert into employee_data values (300, '444', 777);
SQL> select * from employee_data;
DEF_ID DEF_VALUE EMP_ID
100 [email protected] 123
200 01232222 123
300 5555 123
100 [email protected] 666
200 888 666
300 999 666
300 999 777
7 rows selected.I'm supposed to create a SQL that will return me the email, mobile_phone, and home_phone for a set of employees. The result will be something like this:
EMPLOYEE ID | HOME_PHONE | MOBILE_PHONE | EMAIL
123 | 5555 | 01232222 | [email protected]
666 | 999 | 888 | [email protected]
777 | 444 | null | nullThe thing I'm finding difficulty here is that the same column is used to store different values, based on the value in employee_definition table (something like a key/value pair). If I do:
SQL> select emp_id, def_value as email from employee_data, employee_definition
2 where employee_data.def_id = employee_definition.def_id
3 and employee_definition.def_name = 'EMAIL';
EMP_ID EMAIL
123 [email protected]
666 [email protected]'s partially ok.. I'm just getting the definition for 'EMAIL'. But how can I get all the values in a single query, knowing that the column stores different values based on def_name?
Oh no, not again.
Entity attribute models always seem like a great idea to people who have been in the profession for five minutes and lack any kind of fundamental knowledge.
It staggers me that someone with 2,345 posts still believes "you need a 'detail table' for [storing multiple telephone numbers]"
"A person can have multiple telephone numbers" is not an excuse to build a tired person_attribute table. Niether is the bizarre proposal by someone with over 4k posts who should know better in an earlier post that EAV models are necessary to support temporal fidelity.
Taken to it's logical conclusion, EAV modelling leads to just two application tables. THINGS and THING_ATTRIBUTES. And when you consider that a THING_ATTRIBUTE is also a THING, why not roll those two tables up into one also? Hmmm, what does THINGS and THING_ATTRIBUTES look like? I know, TABLES and COLUMNS. Who would've guessed? SQL already provides the completely flexible extensible attribute model the advocates of EAV proscribe. But it also has data types, physical data independence, constraints and an efficient query language which EAV does not.
EAV modelling errodes the semantics of the attributes which are bundled into the "attribute" table.
There is no point in storing 12 different phone numbers with implied functional dependency to unconstrained and often repeating notional attributes like "MOBILE", "LANDLINE", "WORK", err, "WORK2", err, "MOBILE2", err, ... when this phone type attribute has no semantic value. When you want to call someone, you invariably want to retrive the prefered_phone_number which may depend on a time of day, or a call context.
These things need to be modelled properly (i.e normalised to BCNF) within the context of the database.
Similar Messages
-
How to get all data from nokia to i5s
how to get all data from nokia E71 to i5s???
if you can put those data in your computer then add it in iTunes. your iPhone 5s should get it thru syncing.
-
Hierarchical query - How to get all parent records - Duplicate post
Hi,
In Oracle, START WITH, CONNECT BY commands will give all the direct and indirect child records. Other way round, is they are command which gives all the parent records till the root? Please let me know. I am working on Oracle 9i Release 2.
Thanks a lot for your help.
Edited by: skv on Nov 21, 2008 11:05 AMDuplicate post.
Hierarchical query - How to get all parent records
Please edit this post heading to duplicate post.
Regards.
Satyaki De. -
How to get all data in a section from profile file?
Suppose I have profile ini have a section like:
[Mysection]
k1 =v1
k2=v2
the key-value pair could be dynamically in this section. then I want to get all data in Mysection. How can I get it in a loop for all in powerscript?This is what you need:
integer li_fhandle, li_rcode = 1, li_sfound = 0, li_idx = 0, li_eqpos, i
string ls_filename = 'C:\app.ini'
string ls_line, as_key[], as_val[]
string ls_section = '[General]'
// OPEN INI FILE
li_fhandle = FileOpen(ls_filename, LineMode!)
IF IsNull(li_fhandle) OR li_fhandle < 1 THEN
// DO NOTHING
ELSE
DO WHILE li_rcode > 0
li_rcode = FileRead(li_fhandle, ls_line)
IF li_rcode > 0 THEN
IF POS(ls_section, ls_line) > 0 THEN
li_sfound = 1
CONTINUE
END IF
IF li_sfound = 0 THEN CONTINUE
IF POS(ls_line, '[') > 0 AND POS(ls_line, ']') > 0 THEN EXIT
li_eqpos = POS(ls_line, '=')
li_idx++
as_key[li_idx] = MID(ls_line, 1, li_eqpos - 1)
as_val[li_idx] = MID(ls_line, li_eqpos + 1)
END IF
LOOP
END IF
FOR i = 1 TO li_idx
messagebox('Key - Value',as_key[i] + ' = ' + as_val[i])
NEXT
// CLOSE INI FILE
IF li_fhandle > 0 THEN
FileClose(li_fhandle)
END IF
Adapt it to your needs... you probably should make it a function. -
How to get all data from time maschine to windows pc?
pls can somebody helps me, i lost my macbook and all data have on time maschine.................... need to get them out on windows pc, and second problem, downloaded itunes to windows but how i can get pictures and music from my ipod and iphone to itunes, thx for every help
if you can put those data in your computer then add it in iTunes. your iPhone 5s should get it thru syncing.
-
How to get ALL data from ipod to new computer with itunes??
I have a ipod touch 2nd gen. I have cd's and purchased songs on my ipod. I did use itunes on my friends computer for a number of years but now I've got windows 7 computer and i have downloaded itunes but it won't let me transfer current data on my ipod to itunes without me loosing it all. I can only access itunes at friends now. Is there any way to get all my songs, playlists, apps (with data still on it) and photos without deleting it? I am looking for the cheapest way possible. I have tried downloading copy software but it all costs money. Thanks
See:
Syncing to a "New" Computer or replacing a "crashed" Hard Drive: Apple Support Communities
Sync Your iOS Device with a New Computer Without Losing Data - How-To Geek
Recovering your iTunes library from your iPod or iOS device: Apple Support Communities -
How to get all data from inputstream?
I have written a program to download pages from web sites,
but sometimes I can't get all the content of the page,
How can I do?//Try the following code:
//It works in all cases (as long as the client is not //hid beneath a or proxy).
import java.net.*;
import java.io.*;
public class webClient {
public static void main(String args[]) {
try{
if(args.length < 1) {
System.out.println("webClient URL");
System.exit(0);
URL u = new URL(args[0]);
BufferedInputStream inputStream = new BufferedInputStream((u.openConnection()).getInputStream());
int n;
byte[] buff = new byte[2048];
ByteArrayOutputStream out = new ByteArrayOutputStream();
while((n = inputStream.read(buff)) >= 0)
out.write(buff, 0, n);
System.out.println(out.toString());
} catch(Exception e) {
e.printStackTrace();
} -
Query:how to get older date and value
Hi,
I am trying to develop a query that gives me the current amount assigned to a user/employee and the previous amount/old amount assigned to the employee.
The query so far looks like this:
select distinct p.ELEMENT_ENTRY_ID
+,p.EFFECTIVE_START_DATE+
+,p.EFFECTIVE_END_DATE+
+,p.LAST_UPDATE_DATE "UPDATE DATE"+
+,to_char(p.LAST_UPDATE_DATE,'MON') MONTH+
+,to_char(p.LAST_UPDATE_DATE,'YYYY') YEAR+
+,p.LAST_UPDATED_BY+
+,u.USER_NAME "ENTERED BY USERNAME"+
+,e1.FULL_NAME "ENTERED BY "+
+,v.EFFECTIVE_START_DATE+
+,v.EFFECTIVE_END_DATE+
+,v.SCREEN_ENTRY_VALUE "NEW AMOUNT"+
+,t.ELEMENT_TYPE_ID+
+,t.INPUT_CURRENCY_CODE "AMOUNT CURRENCY",t.ELEMENT_NAME+
+,t.DESCRIPTION+
+,e.FULL_NAME "ASSIGNED TO"+
from
pay_element_entries_f p
+,PAY_ELEMENT_ENTRY_VALUES_F v+
+,pay_element_types_f t+
+,PER_ALL_ASSIGNMENTS_F a+
+,per_all_people_f e+
+,fnd_user u+
+,per_all_people_f e1+
where
p.ELEMENT_ENTRY_ID=v.ELEMENT_ENTRY_ID
and p.EFFECTIVE_END_DATE=v.EFFECTIVE_END_DATE
and t.ELEMENT_TYPE_ID=p.ELEMENT_TYPE_ID
and t.BUSINESS_GROUP_ID=229
and a.ASSIGNMENT_ID=p.ASSIGNMENT_ID
and e.PERSON_ID=a.PERSON_ID
and p.LAST_UPDATED_BY=u.USER_ID
and v.SCREEN_ENTRY_VALUE <>'NULL'
and u.PERSON_PARTY_ID=e1.PARTY_ID()+
and p.CREATOR_TYPE <> 'F'
and e.EFFECTIVE_END_DATE> sysdate
and p.CREATOR_TYPE='SP'
and p.EFFECTIVE_END_DATE>sysdate
I need the older value of v.SCREEN_ENTRY_VALUE and the ,*v.EFFECTIVE_START_DATE*
*,v.EFFECTIVE_END_DATE* columns may vary from one employee to another and there could be more than two older values for each employee.
Any suggesions please.....AHS wrote:
Any suggesions please.....Yes.
1) post your Oracle version
select * from v$version;2) post some create table DDL and sample data (in the form of insert statements) so we have an idea of what you're starting with (this would be after you come up with a small, but complete example of your problem)
3) show us sample output representing the correct results based on the data in step # the second.
4) format your code with the tags -
How to get max date field in the query
Hi,
We uploads the data into the cube every week.
Basically we are planning to put some ticker on the query. This ticker will show the user, upto which date the data is available in the cube.
I want the query, which will show me only the maximum date (maximum 0calday) from the infocube in the report.
This in turn, I will use in the ticker and make use of it.
Can anyone please help in making this query.
Thanks
Ramesh Ganjiif 0CALDAY is used as a characteristic then you have to convert that as a key figure using a replacement path variable.
Please see the below link for changing 0CALDAY as a key figure using Replacement path
http://www.sd-solutions.com/documents/SDS_BW_Replacement%20Path%20Variables.html
https://websmp106.sap-ag.de/~sapdownload/011000358700001963972003E/HowToCalcWithAttr.pdf
Now you have to create an exception "Top N Rows" based on the replacement path variable created above.
This will solve your problem.
Regs
Gopi.
Award points if it helps ... -
Hierarchical query - How to get all parent records
Hi,
In Oracle, START WITH, CONNECT BY commands will give all the direct and indirect child records. Other way round, is they are command which gives all the parent records till the root? Please let me know. I am working on Oracle 9i Release 2.
Thanks a lot for your help.Hi - I believe what you want is the "SYS_CONNECT_BY_PATH" function (research it in the SQL Reference Guide).
Here is an exampe:
SELECT empno
, ename
, mgr
, LTRIM (SYS_CONNECT_BY_PATH (ename, ' -> '), ' ->') AS emp_path
, LEVEL AS emp_level
FROM scott.emp
CONNECT BY PRIOR empno = mgr
START WITH mgr IS NULL;
Result:
EMPNO ENAME MGR EMP_PATH EMP_LEVEL
7839 KING KING 1
7566 JONES 7839 KING -> JONES 2
7788 SCOTT 7566 KING -> JONES -> SCOTT 3
7876 ADAMS 7788 KING -> JONES -> SCOTT -> ADAM 4
7902 FORD 7566 KING -> JONES -> FORD 3
7369 SMITH 7902 KING -> JONES -> FORD -> SMITH 4
7698 BLAKE 7839 KING -> BLAKE 2
7499 ALLEN 7698 KING -> BLAKE -> ALLEN 3
7521 WARD 7698 KING -> BLAKE -> WARD 3
7654 MARTIN 7698 KING -> BLAKE -> MARTIN 3
7844 TURNER 7698 KING -> BLAKE -> TURNER 3
7900 JAMES 7698 KING -> BLAKE -> JAMES 3
7782 CLARK 7839 KING -> CLARK 2
7934 MILLER 7782 KING -> CLARK -> MILLER 3
14 rows selected.Good luck... -
How to get the data from multiple tabes into single table
hi all,
here i am having 10 data base tables,how to get the data into a single table.
regards,
subba reddyhi,
non XI/PI related
Regards,
Michal Krawczyk -
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 -
How to Get Missing Dates for Each Support Ticket In My Query?
Hello -
I'm really baffled as to how to get missing dates for each support ticket in my query. I did a search for this and found several CTE's however they only provide ways to find missing dates in a date table rather than missing dates for another column
in a table. Let me explain a bit further here -
I have a query which has a list of support tickets for the month of January. Each support ticket is supposed to be updated daily by a support rep, however that isn't happening so the business wants to know for each ticket which dates have NOT been
updated. So, for example, I might have support ticket 44BS which was updated on 2014-01-01, 2014-01-05, 2014-01-07. Each time the ticket is updated a new row is inserted into the table. I need a query which will return the missing dates per
each support ticket.
I should also add that I DO NOT have any sort of admin nor write permissions to the database...none at all. My team has tried and they won't give 'em. So proposing a function or storable solution will not work. I'm stuck with doing everything
in a query.
I'll try and provide some sample data as an example -
CREATE TABLE #Tickets
TicketNo VARCHAR(4)
,DateUpdated DATE
INSERT INTO #Tickets VALUES ('44BS', '2014-01-01')
INSERT INTO #Tickets VALUES ('44BS', '2014-01-05')
INSERT INTO #Tickets VALUES ('44BS', '2014-01-07')
INSERT INTO #Tickets VALUES ('32VT', '2014-01-03')
INSERT INTO #Tickets VALUES ('32VT', '2014-01-09')
INSERT INTO #Tickets VALUES ('32VT', '2014-01-11')
So for ticket 44BS, I need to return the missing dates between January 1st and January 5th, again between January 5th and January 7th. A set-based solution would be best.
I'm sure this is easier than i'm making it. However, after playing around for a couple of hours my head hurts and I need sleep. If anyone can help, you'd be a job-saver :)
Thanks!!CREATE TABLE #Tickets (
TicketNo VARCHAR(4)
,DateUpdated DATETIME
GO
INSERT INTO #Tickets
VALUES (
'44BS'
,'2014-01-01'
INSERT INTO #Tickets
VALUES (
'44BS'
,'2014-01-05'
INSERT INTO #Tickets
VALUES (
'44BS'
,'2014-01-07'
INSERT INTO #Tickets
VALUES (
'32VT'
,'2014-01-03'
INSERT INTO #Tickets
VALUES (
'32VT'
,'2014-01-09'
INSERT INTO #Tickets
VALUES (
'32VT'
,'2014-01-11'
GO
GO
SELECT *
FROM #Tickets
GO
GO
CREATE TABLE #tempDist (
NRow INT
,TicketNo VARCHAR(4)
,MinDate DATETIME
,MaxDate DATETIME
GO
CREATE TABLE #tempUnUserdDate (
TicketNo VARCHAR(4)
,MissDate DATETIME
GO
INSERT INTO #tempDist
SELECT Row_Number() OVER (
ORDER BY TicketNo
) AS NROw
,TicketNo
,Min(DateUpdated) AS MinDate
,MAx(DateUpdated) AS MaxDate
FROM #Tickets
GROUP BY TicketNo
SELECT *
FROM #tempDist
GO
-- Get the number of rows in the looping table
DECLARE @RowCount INT
SET @RowCount = (
SELECT COUNT(TicketNo)
FROM #tempDist
-- Declare an iterator
DECLARE @I INT
-- Initialize the iterator
SET @I = 1
-- Loop through the rows of a table @myTable
WHILE (@I <= @RowCount)
BEGIN
-- Declare variables to hold the data which we get after looping each record
DECLARE @MyDate DATETIME
DECLARE @TicketNo VARCHAR(50)
,@MinDate DATETIME
,@MaxDate DATETIME
-- Get the data from table and set to variables
SELECT @TicketNo = TicketNo
,@MinDate = MinDate
,@MaxDate = MaxDate
FROM #tempDist
WHERE NRow = @I
SET @MyDate = @MinDate
WHILE @MaxDate > @MyDate
BEGIN
IF NOT EXISTS (
SELECT *
FROM #Tickets
WHERE TicketNo = @TicketNo
AND DateUpdated = @MyDate
BEGIN
INSERT INTO #tempUnUserdDate
VALUES (
@TicketNo
,@MyDate
END
SET @MyDate = dateadd(d, 1, @MyDate)
END
SET @I = @I + 1
END
GO
SELECT *
FROM #tempUnUserdDate
GO
GO
DROP TABLE #tickets
GO
DROP TABLE #tempDist
GO
DROP TABLE #tempUnUserdDate
Thanks,
Shridhar J Joshi
<If the post was helpful mark as 'Helpful' and if the post answered your query, mark as 'Answered'> -
How to get max date in variable using dynamic query
Hi,
the following code gets all dates from sourcetable i want only max date , so i thought max function can be added and it will work
but still i have to create a table for one value(scalar) can get it in any other effeciant way.
declare
TYPE date_string IS TABLE OF VARCHAR(1000);
date_obj date_string;
BEGIN
EXECUTE IMMEDIATE 'SELECT to_char('''||day1||'-'||month1||'-'||year1||''') FROM '||source_schema||'.'|| sourcetable ||'' bulk collect INTO date_obj;
FOR indx IN date_obj.FIRST..date_obj.LAST loop
dbms_output.put_line(
date_obj(indx));
END loop;
DBMS_OUTPUT.PUT_LINE('Sample output');
END;
yours sincerely944768 wrote:
the following code gets all dates from sourcetableNo it doesn't. What is the datatype of day1, month1 and year1? They cannot be DATE datatypes otherwise your TO_CHAR would fail with all that concatenation going on. And your TO_CHAR is returning a VARCHAR2 datatype... so you cannot say that it is getting all dates... because there are no DATE datatypes returned. It's getting a lot of strings, but certainly not DATE's.
i want only max date , so i thought max function can be added and it will work You can use the MAX function on a DATE datatype, but not on strings (at least not in the way you intend it to work).
Converting it to a DATE before doing the MAX will allow you to get the maximum date (assuming the date format is correct)
EXECUTE IMMEDIATE 'SELECT max(to_date(to_char('''||day1||'-'||month1||'-'||year1||'''),''DD-MM-YYYY'')) FROM '||source_schema||'.'|| sourcetable ||'' bulk collect INTO date_obj;Then you will find have the other issues...
a) you are then going to be fetching your DATEs in to a collection of VARCHAR strings. (Not even VARCHAR2, very poor). This should be DATE datatype
b) you are bulk collecting into a collection, when you are using MAX which will return a single value in your example
And you really should address the design issues:
c) why are day, month and year, not being stored in the database as a single DATE datatype in the first place
d) why does your code not know the name of the table it's querying requiring the use of very poor dynamic SQL techniques.
e) why are you loading data in a collection in expensive PGA memory... what can't you do in SQL that requires you to collect the data into memory first? -
How to get master data records that do not have transaction data in a query
Hi,
How to get master data records that do not have transaction data in a query output. Can we create a query or any other way to get the master data records that do not have transaction data?Hi,
Create a multiprovider which includes transactional data target and master data info object. Make sure that identification for this master data info object is ticked on both the provider.
Create report on this multiprovider , keep the master data info object in rows , and now you should able to see all the values which are there in master data info object irrespective of transaction happened or not .
Next you may create condition showing only zero keyfigure values , ie. master data without any transaction.
Hope that helps.
Regards
Mr Kapadia
Maybe you are looking for
-
Newbie question: how to send mails on a Solaris 10 machine?
Good morning all, I am responsible of a lab, containing some Solaris machines. On one of those machines, a collegue would like to send mails, using following command: echo "something" | mailx -v -s "subject" <collegue>@<domain>.comThe mentioned e-mai
-
Will Final Cut allow for Time Lapse Photography for days?
I have a new MacBook and am unable to use my old editing software from my powerbook so am needing to find a program that will allow me to hook up my video camera and let it record for possibly a full 24 hours, will FC let me do this? I used to use th
-
Logic Pro 8 Crashing on startup after OS upgrade
I recently upgraded to Snow Leopard in order to sync my new iPhone. Now Logic Pro 8 and a few other audio programs are all crashing on startup. When I open Logic, It scans thru my plugins and displays the box that says Logic 8, and shortly after it
-
I got Apple TV 6.0 to work by doing this...
So I tried the update and got the connect to iTunes loop of death also. After a number of seemingly pointless iterations to get it out of that... I finally got it to work by going to Download iTunes Now and getting the latest revision of iTunes 11.1
-
Generic extractor Delta problem
hello, i have created a Generic extractor based on the AUFM table and the delta field is MBLNR (Material document no) that is a numeric pointer used for delta. My problem is that when i pull the delta not all records are being pulled. Why is that so?