Writing sql query
Hello,
I have a string like a:b:c:d:e:f
I would like to fetch a and b values as 2 separate columns.
Using oracle 10g.
Thanks
Try:
SQL> variable test_str varchar2(20)
SQL> exec :test_str :='a:b:c:d:e:f';
PL/SQL procedure successfully completed.
SQL> ed
Wrote file afiedt.buf
1 select
2 trim( substr (txt,
3 instr (txt, ':', 1, level ) + 1,
4 instr (txt, ':', 1, level+1)
5 - instr (txt, ':', 1, level) -1 ) )
6 as token
7 from (select ':'||:test_str||':' txt
8 from dual)
9 connect by level <=
10* length(:test_str)-length(replace(:test_str,':',''))+1
SQL> /
TOKEN
a
b
c
d
e
f
6 rows selected.
Similar Messages
-
i am trying to write sql query for a single recordset.
I have an items table with all the standard item info and an item_colorID.
i have a color_lookup table with 2 columns, item_colorID and color_ID
i have a colors table with 2 columns, color_ID and color
i want to join the tables and filter it so that a repeat region shows dynamic data of item name, description, thumb, price
and also a list/menu dynamically populated by color
filtered so that each item shows in the list/menu only the colors that the item has available.
i have tried different variations of this sql
SELECT * FROM items INNER JOIN color_lookup ON color_lookup.item_colorID = items.item_colorID INNER JOIN colors ON colors.color_ID = color_lookup.color_ID WHERE items.itemCatID = 3 ORDER BY items.itemName
but the list/menu shows every color choice multiplied by the number of items in that color
ie White will show 80+ times.
thanks for your help,
jim balthropbregent,
thanks for your help.
I am building a shopping cart and i have a recordset to list the items and a repeat region for that recordset
i have a second recordset for the colors joined to the item_colorID nested inside the repeat region.
the shopping cart software has a 'lookup from recordset' choice for the add to cart servior behavior
and then i bind to the columns on the cart page.
it produces this code
if (isset($totalRows_rs_itemscat3) && $totalRows_rs_itemscat3 > 0) {
$row_rs_itemscat3 = WAEC_findRecordMySQL($rs_itemscat3, "item_ID", $ATC_itemID);
if ($row_rs_itemscat3) {
$ATC_itemName = "".$row_rs_itemscat3['itemName'] ."";// column binding
$ATC_itemDescription = "".$row_rs_itemscat3['itemShortDesc'] ."";// column binding
$ATC_itemWeight = floatval("".$row_rs_itemscat3['itemWeight'] ."");// column binding
$ATC_itemQuantity = "".$_POST["Farrington_1_Quantity_Add"] ."";// column binding
$ATC_itemPrice = floatval("".$row_rs_itemscat3['itemPrice'] ."");// column binding
$ATC_itemThumbnail = "".$row_rs_itemscat3['itemThumb'] ."";// column binding
$ATC_itemcolorchoice = "".$row_rs_colors['color'] ."";// column binding
mysql_data_seek($rs_itemscat3, 0);
$row_rs_itemscat3 = mysql_fetch_assoc($rs_itemscat3);
the column binding for the colors is from a different recordset and when redirecting to the cart page the color info will not show.
So my thinking is if i could get the color list/menu to populate from the same recordset as the item listing, it would solve my add to cart server behavior.
Is it possible to do this with only one recordset?
the products page and the cart page can be seen
http://www.farrington-enterprises.com/rain-gutters.php
add an item to the cart with any color choice and the color info does not carry to the cart. -
I am getting small erro when i am writing sql query
hi all
in dashboard prompts i am trying to write small query (select 1 from dual) in sql request
but i am getting following error
State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 27004] Unresolved table: "dual". (HY000)
SQL Issued: select 1 from dual
my problem is i want to put result of function in the prompt so, i am testing with small one
so hw can i call the function from prompts
select updae_fn(pp,rr) from dual
but it is giving an error that is syntax error '(' is missing but that was there
Thanks
Sreedharhi ,
Dual is not supported by OBIEE
select updae_fn(pp,rr) from dualUSe evaluate function and include the function
http://oracle-bi.siebelunleashed.com/articles/callingdb-function-in-obiee/
thanks,
Saichand.v
Edited by: Saichand Varanasi on Oct 7, 2010 12:48 PM -
how can i best re-write the following query. i want to re-write the following sql into something more readable and less line if possible. how can i re-write it
SELECT z.as_cd, z.sass, z.elem_desc
FROM
SELECT a.as_cd, a.sass b.elem_desc
FROM
SELECT DISTINCT as_cd,NVL (as_sub_cd, as_cd) AS sass
FROM b2c
WHERE bdate = p_date
) a,
SELECT /*+ no_merge*/ DISTINCT elem, elem_desc
FROM desc
WHERE ename = 'Class'
) b
WHERE a.as_cd IS NOT NULL
AND a.as_cd = b.elem(+)
) z,
SELECT DISTINCT elem, elem_desc
FROM desc
WHERE ename = 'Sub Class'
) t
WHERE z.sass = t.elem(+)Try this:
SELECT DISTINCT z.as_cd, z.sass, z.elem_desc
FROM desc t,
(SELECT DISTINCT a.as_cd, NVL (a.as_sub_cd, a.as_cd) sass, b.elem_desc
FROM b2c a, desc b
WHERE a.as_cd IS NOT NULL
AND a.as_cd = b.elem(+)
AND b.ename = 'Class'
AND a.bdate = p_date) z
WHERE z.sass = t.elem(+)
AND t.ename = 'Sub Class'; -
Hi evrybody,
I have a requirement which seems very wierd to me, I m unable to clue it also. Please help me in writing the same.
I have a column in a table which contains the data with spaces and everythng same as below:
SUBSCRIBER LINE TEST
VERSION 2
DEV SNB MP FCODE
LIBA-13 4222430012 11 3
FOREIGN VOLTAGE TESTS
DC AC
FVAE FVBE FVAB FVAE FVBE FVAB
LACC LACC 7.4 0.1 0.1 0.1
0.0 0.0 PASS PASS PASS PASS
PASS PASS
INSULATION RESISTANCE TESTS
IRAE IRBE IRABA IRBBA IRAB
LACC LACC LACC LACC 8113K
10000K >10000K >10000K >10000K PASSPASS PASS PASS PASS
CAPACITANCE MEASUREMENTS
CAE CBE CAB BRK
LACC LACC 4428 NO
68 72
NT LOOPBACK TEST
PASS
NT DC SIGNATURE TEST
V-HIGH V-LOW
83.920K LACC
PASS >10000K
PASS
NT CONNECTED
INV
CIRCUIT TEST RESULT
FAIL
I need to get the o/p as:
FVAELACC=0.0 FVBELACC=0.0 FVAB=7.4 FVAE=0.1 FVBE=0.1 FVAB=0.1
CAELACC=68 CBELACC=72 CAB=4428
NT CONNECTED=INV..
Thanks in advance.Evrybody thanks for advices. My Question is little unclear but the requirement is that itself.. Anyways I got the O/p finally.
Mr. Shahzad ,if any of the questions makes u feel like wasting ur technical time, jus donot read it.. The people who can undertsand the problem, they can answer to the post. If the requirement is like that, none of us are helpless. -
How can i achive this result by writing SQL Query ?
Dear Exparts,
Here is my banner
Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Prod
PL/SQL Release 10.2.0.3.0 - Production
"CORE 10.2.0.3.0 Production"
TNS for 32-bit Windows: Version 10.2.0.3.0 - Production
NLSRTL Version 10.2.0.3.0 - ProductionI have two table with relation. Here is the scripts of create table and insert data.
TABLE
CREATE TABLE TAB1
T1_ID NUMBER(5)
, T1_NAME VARCHAR2(100)
ALTER TABLE TAB1
MODIFY (T1_ID NOT NULL);
ALTER TABLE TAB1
ADD CONSTRAINT TAB1_PK PRIMARY KEY
T1_ID
ENABLE;
CREATE TABLE TAB2
T2_ID NUMBER(5) NOT NULL
, T2_T1_ID NUMBER(5)
, T2_RV_NO VARCHAR2(20)
, T2_RV_DATE DATE
, T2_F1 VARCHAR2(20)
, T2_F2 VARCHAR2(20)
, T2_F3 VARCHAR2(20)
, CONSTRAINT TAB2_PK PRIMARY KEY
T2_ID
ENABLE
ALTER TABLE TAB2
ADD CONSTRAINT TAB2_TAB1_FK1 FOREIGN KEY
T2_T1_ID
REFERENCES TAB1
T1_ID
ENABLE;INSERT DATA
Insert into TAB1 (T1_ID,T1_NAME) values (1,'Test 1');
Insert into TAB1 (T1_ID,T1_NAME) values (2,'Test 2');
Insert into TAB2 (T2_ID,T2_T1_ID,T2_RV_NO,T2_RV_DATE,T2_F1,T2_F2,T2_F3) values (1,1,'00',to_date('01-OCT-2012','DD-MON-RRRR'),'Probation','05','Yes');
Insert into TAB2 (T2_ID,T2_T1_ID,T2_RV_NO,T2_RV_DATE,T2_F1,T2_F2,T2_F3) values (2,1,'01',to_date('06-OCT-2012','DD-MON-RRRR'),'Confirm','06','Yes');
Insert into TAB2 (T2_ID,T2_T1_ID,T2_RV_NO,T2_RV_DATE,T2_F1,T2_F2,T2_F3) values (3,2,'00',to_date('02-OCT-2012','DD-MON-RRRR'),'Probation','07','No');
Insert into TAB2 (T2_ID,T2_T1_ID,T2_RV_NO,T2_RV_DATE,T2_F1,T2_F2,T2_F3) values (4,2,'01',to_date('09-OCT-2012','DD-MON-RRRR'),'Probation','07','Yes');
Insert into TAB2 (T2_ID,T2_T1_ID,T2_RV_NO,T2_RV_DATE,T2_F1,T2_F2,T2_F3) values (5,1,'02',to_date('10-OCT-2012','DD-MON-RRRR'),'Confirm','06','No');Now i want to produce the following reports..
Period: 06-OCT-2012 to 09-OCT-2012
T2_RV_DATE T1_NAME T2_RV_NO Revised_Column Previous_Value Revised_value
06-OCT-2012 Test 1 01 T2_F1 Probation Confirm
T2_F2 05 06
09-OCT-2012 Test 2 01 T2_F3 No YesI just achieve Revised_Column Previous_Value Revised_value for a particular name.
Here is my code
SELECT T2_RV_NO,T2_RV_DATE,T1_NAME,'T2_F1' Revised_Column,PREVIOUS_VALUE,REVISED_VALUE
FROM(
SELECT T2_RV_NO,T2_RV_DATE,T1_NAME,'T2_F1',
LAG(T2_F1) OVER (ORDER BY T2_RV_DATE) PREVIOUS_VALUE ,T2_F1 REVISED_VALUE
FROM TAB2,TAB1
WHERE TAB1.T1_ID=TAB2.T2_T1_ID
AND TAB1.T1_ID=:EMP_ID)
WHERE NVL(PREVIOUS_VALUE,'null')<>NVL(REVISED_VALUE,'null')
AND T2_RV_DATE BETWEEN :BEGIN_DATE AND :END_DATE
AND T2_RV_NO<>'00'
UNION ALL
SELECT T2_RV_NO,T2_RV_DATE,T1_NAME,'T2_F2' Revised_Column,PREVIOUS_VALUE,REVISED_VALUE
FROM(
SELECT T2_RV_NO,T2_RV_DATE,T1_NAME,'T2_F2',
LAG(T2_F2) OVER (ORDER BY T2_RV_DATE) PREVIOUS_VALUE ,T2_F2 REVISED_VALUE
FROM TAB2,TAB1
WHERE TAB1.T1_ID=TAB2.T2_T1_ID
AND TAB1.T1_ID=:EMP_ID)
WHERE NVL(PREVIOUS_VALUE,'null')<>NVL(REVISED_VALUE,'null')
AND T2_RV_DATE BETWEEN :BEGIN_DATE AND :END_DATE
AND T2_RV_NO<>'00'
UNION ALL
SELECT T2_RV_NO,T2_RV_DATE,T1_NAME,'T2_F3' Revised_Column,PREVIOUS_VALUE,REVISED_VALUE
FROM(
SELECT T2_RV_NO,T2_RV_DATE,T1_NAME,'T2_F3',
LAG(T2_F3) OVER (ORDER BY T2_RV_DATE) PREVIOUS_VALUE ,T2_F3 REVISED_VALUE
FROM TAB2,TAB1
WHERE TAB1.T1_ID=TAB2.T2_T1_ID
AND TAB1.T1_ID=:EMP_ID)
WHERE NVL(PREVIOUS_VALUE,'null')<>NVL(REVISED_VALUE,'null')
AND T2_RV_DATE BETWEEN :BEGIN_DATE AND :END_DATE
AND T2_RV_NO<>'00'but it's not work for multiple employee id
Thanks in advance
Edited by: Asked to Learn on Oct 6, 2012 9:18 PMAsked to Learn wrote:
thanks members. i get a solution of my own for my reporting purpos. Thanks..Well why don't you post your solution? Why not be helpful to others like yourself who might search the forum looking for answers? Don't just take, give back.
Cheers, APC -
Need help in writing SQL query
Hi,
I have a rquirement where I need to convert columns into records.
Table1:
(note: I have around 150 columns i.e period1 to period150)
unit startdate Period1 period2 period3 period4 period5
A 1/1/2011 100 200 300 400 500
Now I need data in below format
UNIT startdate period
A 1/1/2011 100
A 1/1/2011 200
A 1/1/2011 300
A 1/1/2011 500
Please suggest me...
Thanks.With UNPIVOT you can "name" each of your rows using as.
One trick is to "name" the rows to a number - then you can add that number of weeks to your start date - like this:
with t as (
select 'A' unit, DATE '2011-01-01' startdate, 100 period1, 200 period2 ,300 period3, 400 period4 ,500 period5 from dual
select
unit,
startdate + numtodsinterval(week*7,'day') startdate,
qty
from t
unpivot(
qty for week in (
period1 as 0,
period2 as 1,
period3 as 2,
period4 as 3,
period5 as 4
;Theoretically the above should work - but somehow I get a NULL date on my 11.1 instance? And I don't have another version to test with, alas.
But try it and see if it works on your instance ;-) -
Hi All,
I am using Oracle Database Version 11.2.
I have a formula (A-B)/[(A-B)/10]. The tables that are holding the rows for this calculations are given below:
ROWS_TAB
====== ===================
Row Amount
====== ===================
A 5000
B -5000
FORMULA_TAB
======== =========== ======== =============
| ROW# | Operator | ROW | CONSTANT |
======== =========== ======== =============
| 10 | E | A | |
| 20 | - | B | |
| 30 | E | A | |
| 40 | - | B | |
| 50 | / | | 10 |
| 60 | / | | |
======== =========== ======== =============
The operator E starts a new calculation. The above formula has two sub-expressions thereby the table has two rows with E. Minus denoted by -, Plus denoted by +, Multiply denoted by *, and Division denoted by /.
I want to write single SQL query to perform this calculation. Is it achievable in SQL?
The scripts used to generate the tables are as below:
create table ROWS_TAB
(row_name VARCHAR2(1),
amount NUMBER);
create table FORMULA_TAB
(row# NUMBER,
operator VARCHAR2(1),
row_name VARCHAR2(1),
constant NUMBER);
INSERT INTO ROWS_TAB VALUES('A', 5000);
INSERT INTO ROWS_TAB VALUES('B', -5000);
INSERT INTO FORMULA_TAB VALUES(10, 'E','A',null);
INSERT INTO FORMULA_TAB VALUES(20, '-','B',null);
INSERT INTO FORMULA_TAB VALUES(30, 'E','A',null);
INSERT INTO FORMULA_TAB VALUES(40, '-','B',null);
INSERT INTO FORMULA_TAB VALUES(50, '/','',10);
INSERT INTO FORMULA_TAB VALUES(60, '/','','');
Can anyone help in writing SQL query....
Thanks in advance
Best Regards
BilalAs Frank said, it would be much easier to simply input the formula. Then, assuming you have OLAP option:
variable formula varchar2(30)
exec :formula := '(A-B)/((A-B)/10)';
with t as (
select *
from rows_tab
model
dimension by(row_number() over(order by row_name) r)
measures(
row_name,
amount,
count(*) over() cnt,
cast(:formula as varchar2(4000)) formula
rules(
formula[any] order by r = replace(nvl(formula[cv() - 1],formula[cv()]),row_name[cv()],amount[cv()])
select :formula || ' = ' || dbms_aw.eval_number(formula) result
from t
where r = cnt
RESULT
(A-B)/((A-B)/10) = 10
SQL>
And if you do not have OLAP, you could use xquery:
with t as (
select *
from rows_tab
model
dimension by(row_number() over(order by row_name) r)
measures(
row_name,
amount,
count(*) over() cnt,
cast(:formula as varchar2(4000)) formula
rules(
formula[any] order by r = replace(nvl(formula[cv() - 1],formula[cv()]),row_name[cv()],amount[cv()])
select :formula || ' = ' || xmlquery(replace(formula,'/',' div ') returning content) result
from t
where r = cnt
RESULT
(A-B)/((A-B)/10) = 10
SQL>
SY. -
How to return SQL query results as resultset
I am developing a site in ASP to support back end as oracle or SQL server.
In SQL Server, from stored procedure it is possible to return resultset by writing sql query in procedure using input parameters as filters (where condition).
Is there a way to return a resultset from oracle procedures or functions.http://asktom.oracle.com/~tkyte/ResultSets/index.html
In 9i or above you no longer need to define your own weak ref cursor type in a package spec, you can use the built-in SYS_REFCURSOR. -
Having trouble writing to a database although SQL query is correct
Hi there. I am trying to write an sql query to a database but I am failing to understand what is going wrong in terms of executing the query.
I have the following code.
static public int writeToStockTable (String suppIn, String nameIn, String typeIn, float quantIn, float priceIn, String descIn, String styleIn, String finishIn) { // Temporary variable to hold the SQL query String SQLString, SQLString2; ResultSet rs = null; // Build a string containing the SQL INSERT instruction to be used later SQLString = "INSERT INTO "+typeIn+" VALUES ('1', '" + suppIn + "', '" + nameIn + "', " + quantIn + ", " + priceIn + ", '"+descIn+"', '"+styleIn+"', '"+finishIn+"')"; SQLString2 = "SELECT Name FROM Suppliers WHERE Name = '" + suppIn + "'"; try { // The createStatement() method creates a Statement object. Object will be // attached to my reference variable (statement) defined at the top of class. statement = connectionToBellFiresDB.createStatement(); // The executeUpdate() statement can be used here to execute an // SQL INSERT instruction. rs = statement.executeQuery (SQLString2); if ((rs == null)) { System.out.println ("Trying to say no supplier"); return (-2); } else { System.out.println (SQLString); statement.executeUpdate (SQLString); } } catch (SQLException exception) { return (-1); // Return -1 if problem writing record to file } return (0); // Return with 0 if record successfully written }
Please ignore the attributes not used, it is very much a work in progress. The command that prints SQLString prints
INSERT INTO Fireplace VALUES ('1', 'a', 'a', 1.0, 1.0, 'a', 'a', 'a')
which is correct, but will return the error code -1 when asked to execute the query. The database jdbc:odbc driver has been initialised in the control panel and the program has no other problems accessing the database as far as i am aware.
Any help would be appreciated, i hate database connections :)Chrift wrote:
Im sorry i dont know what you mean by eating the exception, im quite a noob at programming to be honest!
How do i print it out and what is a stack trace?Do you know what an exception is? If not, then you should stay far away from JDBC/Database programming for the time being.
Read [the Exception Tutorial|http://java.sun.com/docs/books/tutorial/essential/exceptions/] first.
Then: an exception has quite a bit of useful information attached that tells you what went wrong.
In your case you catch the exception and ignore everything it could tell you by simply returning -1. Returning 0 and -1 to indicate success/failure is a very bad idea and should not be used in Java code, it's a C-style convention for C-era programming languages. In Java you use exceptions instead.
For starters you could simply add "exception.printStackTrace()" in your catch-block to get some more information out of the exception. -
Sql query writing best practises
HI forum,
Any body is having a tutorial on sql query writing best practises...pls share with me
ThanksFor example:
[url http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/toc.htm]Oracle Database Performance Tuning Guide 10g Release 2 (10.2)
[url http://people.aapt.net.au/roxsco/tuning/]Oracle SQL Tuning Guide
Gints Plivna
http://www.gplivna.eu -
Problem writing a sql query for a select list based on a static LOV
Hi,
I have the following table...
VALIDATIONS
ID Number (PK)
APP_ID Number
REQUESTED Date
APPROVED Date
VALID_TIL Date
DEPT_ID Number (FK)
I have a search form with the following field item variables...
P11_DEPT_ID (select list based on dynamic LOV from depts table)
P11_VALID (select list based on static Yes/No LOV)
A report on the columns of the Validations table is shown based on the values in the search form. So far, my sql query for the report is...
SELECT v.APP_ID,
v.REQUESTED,
v.APPROVED,
v.VALID_TIL,
d.DEPT
FROM DEPTS d, VALIDATIONS v
WHERE d.DEPT_ID = v.DEPT_ID(+)
AND (d.DEPT_ID = :P11_DEPT_ID OR :P11_DEPT_ID = -1)
This query works so far. My problem is that I don't know how to do a search based on the P11_VALID item - if 'yes' is selected, then the VALID_TIL date is still valid. If 'no' is selected then the VALID_TIL date has passed.
Can anyone help me to extend my query to include this situation?
Thanks.Hello !
Let's have a look at my example:create table test
id number
,valid_til date
insert into test values( 1, sysdate-3 );
insert into test values( 2, sysdate-2 );
insert into test values( 3, sysdate-1 );
insert into test values( 4, sysdate );
insert into test values( 5, sysdate+1 );
insert into test values( 6, sysdate+2 );
commit;
select * from test;
def til=yes
select *
from test
where decode(sign(trunc(valid_til)-trunc(sysdate)),1,1,0,1,-1)
=decode('&til','yes',1,-1);
def til=no
select *
from test
where decode(sign(trunc(valid_til)-trunc(sysdate)),1,1,0,1,-1)
=decode('&til','yes',1,-1);
drop table test; It's working fine, I've tested it.
The above changes to my first idea I did because of time portion of the DATE datatype in Oracle and therefore the wrong result for today.
For understandings:
1.) TRUNC removes the time part of DATE
2.) The difference of to date-values is the number of days between.
3.) SIGN is the mathematical function and gives -1,0 or +1 according to an negative, zero or positiv argument.
4.) DECODE is like an IF.
Inspect your LOV for the returning values. According to my example they shoul be 'yes' and 'no'. If your values are different, you may have to modify the DECODE.
Good luck,
Heinz -
Writing a function to find whether a value is present in a sql query output
Hi gurus,
I would like to write a function to which i will pass a value and a sql query as parameters.
Now the function needs to execute that sql query and find whether the given value is present in the output list
when the query is executed. If it is present it should return 'T' otherwise 'F'
My function will look like
CREATE FUNCTION CHECK_VALUE(VALUE VARCHAR2,V_SQL VARCHAR2) RETURN VARCHAR2
SELECT CHECK_VALUE('Dallas','SELECT LOCATION_CODE FROM HR_LOCATIONS')
It should check whether the value 'Dallas' is present in the output list returned by the sql query.
Any help will be appreciated.
Thank you.CREATE OR REPLACE
FUNCTION CHECK_VALUE(
VALUE VARCHAR2,
V_SQL VARCHAR2
RETURN VARCHAR2
IS
RETVAL VARCHAR2(4000);
REFCUR SYS_REFCURSOR;
BEGIN
OPEN REFCUR FOR V_SQL;
LOOP
FETCH REFCUR INTO RETVAL;
EXIT WHEN REFCUR%NOTFOUND;
IF RETVAL = VALUE
THEN
CLOSE REFCUR;
RETURN 'T';
END IF;
END LOOP;
CLOSE REFCUR;
RETURN 'F';
END;
Function created.
SQL> SET SERVEROUTPUT ON
SQL> EXEC DBMS_OUTPUT.PUT_LINE(CHECK_VALUE('DALLAS','select loc from dept'));
T
PL/SQL procedure successfully completed.
SQL> EXEC DBMS_OUTPUT.PUT_LINE(CHECK_VALUE('PARIS','select loc from dept'));
F
PL/SQL procedure successfully completed.
SQL> SY. -
hello ,
I am a beginner in terms of writing sql queries. I hope some body can help me out.
I have two tables
mysql> desc user_group_t;
---------------------------------------------------+
| Field | Type | Null | Key | Default | Extra |
---------------------------------------------------+
| userAccountId | char(8) | | PRI | | |
| groupId | char(8) | | PRI | | |
---------------------------------------------------+
2 rows in set (0.00 sec)
mysql> desc group_t;
---------------------------------------------------+
| Field | Type | Null | Key | Default | Extra |
---------------------------------------------------+
| id | char(8) | | PRI | | |
| name | char(50) | YES | | NULL | |
| email | char(100) | YES | | NULL | |
| description | char(254) | YES | | NULL | |
| parentId | char(8) | YES | | NULL | |
| creatorId | char(8) | YES | | NULL | |
| createDate | char(20) | YES | | NULL | |
| updateDate | char(20) | YES | | NULL | |
| updatorId | char(8) | YES | | NULL | |
---------------------------------------------------+
9 rows in set (0.00 sec)
what I want is list of all groups with id,name and #of members(which is the # of rows in the user_group_t for any given id). Importantly I need the groups with 0 members also to be listed. In short my output should contain exactly the same number of rows as in group_t table with an additional column indicating # of members for that group.
Any help would be greatly appreciated.
Thanks in Advance.
-VasanthThanks Donald,
Actually I figured it out, with the following query:
select id,name,sum(if(groupid is not null,1,0)) as members from group_t left join user_group_t on id=groupid group by id;
I tried your solution, but mysql says there is an error at '+' . Anyway I modified your solution to the one below and it worked.
select a.id, a.name, count(b.groupid) from group_t a left join user_group_t b on a.id=b.groupid group by a.id, a.name;
I tried that before but then I used Count(*) instead of count on groupid. Your solution is elagant and I will go with yours.
Thanks again.
Vasanth -
How to run a SQL query which is stored in a column using PL/SQL?
Hello
I have a table A and one of the column values is select * from emp where empno :=xyz;
Now I would like to call this SQL query using a cursor in PL/SQL and run this for all the empno's and insert them into a temp table.
Can anybody help me in writing this PL/SQL query?
With Regards,
Mohanuser525114 wrote:
The primary reason for doing this is we are calculating percentiles on an entity sales for different range periods, and there are several sql queries stored in a cloumn, so we would like to know whether we can run these queries by calling them in a pl/sql query, Its not necessary that we need to use a cursor, but once fetching the result set of the query we would like to insert them in a table.Vamsi,
As said in response to Satya, executing dynamic SQL, looping over the result set and inserting the results one by one in a temporary table, is a horribly bad idea. Especially in terms of performance, but also regarding the maintainability of your code. It's just way more complex than necessary.
If you want to calculate percentages, then use analytic or aggregate functions in SQL to do so. If you want to store them, use a single INSERT SELECT statement.
If you want to continue on the same path, use Satya's code and use it inside a loop.
Regards,
Rob.
Maybe you are looking for
-
More insight on divs with fluid grids please!
Help me come further up the CS6 fluid grid learning curve, please! I'm adapting an exiting site to fluid grids. After creating the template for the primary pages, I have two major issues at this point(yeah, only two, SO FAR). 1- I have a vertically e
-
been working for 4 hours to get this thing to work.
-
Pages & AppleScript - adding content and new pages
I build iOS apps for a living and I am taking a stab at making a developer's guide for each app I create (classes and methods used, some terminology, etc.). I'm able to get a list of all my class files and methods of each class from XCode using Apple
-
Embedding an file within another
Basically i want to embed a few files, for example pngs image between some xml tags in a new file. How can I store the file between the tags? I've tried to store a string based on a byte array for the file, however this doesn't seem to work and I thi
-
How do I recover Apps Data from the iCloud on iPhone 4S with IOS 6.1?
How do I recover Apps Data from the iCloud on iPhone 4S with IOS 6.1?