Sql query usig round and decode together
can i get one sql quer for returning whole number using round and decode function
eg:
the value 47
if value=47
then
the query should return 50
if the value =44
then
the quer should return 40
pls give me sql query for above example using round and decode function
Edited by: user11368167 on Jul 9, 2009 3:35 AM
A wild guess. If you want the ROUND Function to work only when your column value is 44 or 47 then you could use something like:
SQL> WITH test_tab AS
2 (SELECT 44 col_1
3 FROM DUAL
4 UNION ALL
5 SELECT 15 col_1
6 FROM DUAL
7 UNION ALL
8 SELECT 47 col_1
9 FROM DUAL
10 UNION ALL
11 SELECT 45 col_1
12 FROM DUAL)
13 -- end of test data
14 SELECT col_1,
15 DECODE (col_1,
16 44, ROUND (col_1, -1),
17 47, ROUND (col_1, -1),
18 col_1
19 ) rounded_value
20 FROM test_tab
21 /
COL_1 ROUNDED_VALUE
44 40
15 15
47 50
45 45
4 rows selected.
SQL> CASE Statement can be used as well instead of DECODE.
Good Luck,
Regards,
Jo
Similar Messages
-
Size of SQL query before execution and after execution
hi all
I need help on how can i find out the size of SQL query before execution and after execution in java
The query can be any query select / insert / update
Can anyone help me if any system tables help to find out the required size i mentioned
Urgent help is required
Thanking in advanceI need the size in terms of bytes
like the rquirement is stated as below
select ................: 10 B , return 250 B
so i need size before and after execution in terms of bytes -
Different LOV behavior between SQL query data model and data template
I have noticed different behavior when using parameters linked to list of values (LOV) of type menu with the multiple selection option enabled and a SQL query data model vs a data template. Here's the example because that first sentence was probably really confusing.
SQL Query:
select
plmc.MonthCode, plmc.ModalityDim, plmc.ModalityName,plmc.RegionDim
from
DataOut.dbo.PatientLabMonthlyCross plmc
where
plmc.MonthCode = 200202
and plmc.RegionDim = 1209
and 1 =
case
when coalesce(:modalityDim,null) is null
then 1
else
case
when plmc.ModalityDim in (:modalityDim)
then 1
else 0
end
end
Putting BI Publisher into debug mode, defining a data model of type SQL Query, defining a parameter called :modalityDim linked to a LOV that allows multiple selections, and selecting a couple of values from the LOV the output of the prepared statement is:
[081607_122647956][][STATEMENT] Sql Query : select
plmc.MonthCode,
plmc.ModalityDim,
plmc.ModalityName,
plmc.RegionDim
from
DataOut.dbo.PatientLabMonthlyCross plmc
where
plmc.MonthCode = 200202
and plmc.RegionDim = 1209
and 1 =
case
when coalesce(?,?,null) is null
then 1
else
case
when plmc.ModalityDim in (?,?)
then 1
else 0
end
end
[081607_122647956][][STATEMENT] 1:6
[081607_122647956][][STATEMENT] 2:7
[081607_122647956][][STATEMENT] 3:6
[081607_122647956][][STATEMENT] 4:7
[081607_122654713][][EVENT] Data Generation Completed...
[081607_122654713][][EVENT] Total Data Generation Time 7.0 seconds
Note how the bind variable :modalityDim was changed into two parameters in the prepared statement.
When I use this same SQL Query in a data template the output is:
[081607_012113018][][STATEMENT] Sql Query : select
plmc.MonthCode,
plmc.ModalityDim,
plmc.ModalityName,
plmc.RegionDim
from
DataOut.dbo.PatientLabMonthlyCross plmc
where
plmc.MonthCode = 200202
and plmc.RegionDim = 1209
and 1 =
case
when coalesce(?,null) is null
then 1
else
case
when plmc.ModalityDim in (?)
then 1
else 0
end
end
[081607_012113018][][STATEMENT] 1:'6','7'
[081607_012113018][][STATEMENT] 2:'6','7'
[081607_012113574][][EXCEPTION] java.sql.SQLException: Syntax error converting the nvarchar value ''6','7'' to a column of data type int.
Note the exception because it is trying to convert the multiple parameter values.
Am I doing something completely wrong here? I really need to use a data template because I will need to link a couple of queries together from different database vendors.
-markThis is for 10.1.3.4 - because in 11g every SQL query is automatially part of a data model.
In 10g SQL query is for simple unrelated SQL queries.
If you need to use advance features such as:
a) multiple SQL queries that are joined in master-detail relation ships
b) before/after report triggers
Then you will need to use the data template, which is an XML description
of the queries, links, and PL/SQL calls.
hope that helps,
Klaus -
SQL query with JSP and WML-parameters
Hey,
Could you help me?
I'm trying to do the following. WML deck card 1 send parameter to same WML deck's card help. I try to read the parameter with JSP in card help by putting the parameter to SQL query, but it doesn't work. I can read the parameter with WML in card help. I can also print the value of the parameter with JSP if I generate WML with JSP.
/*parameter sending from card 1 to card help*/
out.println("<go href='#helpcard'>");
out.println("<setvar name='valittukurssi' value='$(valittukurssi)'/>");
/*parameter read with WML in card help */
<p>Valitse kurssi.
$valittukurssi</p>
/'parameter read with JSP by generating WML with JSP*/
out.println("<p>$valittukurssi</p>");
/* SQL query with JSP */
ResultSet uudettulokset = uusilause.executeQuery("select * from kurssi where lyhenne='$valittukurssi'");
Thanks,
RampeYou're problem is easy to fix. You're confusing WML variables with JSP variables. See below:
>
/*parameter sending from card 1 to card help*/
out.println("<go href='#helpcard'>");
out.println("<setvar name='valittukurssi'
value='$(valittukurssi)'/>");
Above you set a var that will work on the phone, not in JSP.
/*parameter read with WML in card help */
<p>Valitse kurssi.
$valittukurssi</p>
Yes the above does display the parameter, because it is a client side WML var, but you cannot use this variable in the JSP code (that's why your SWL fails).
/'parameter read with JSP by generating WML with
JSP*/
out.println("<p>$valittukurssi</p>");Here's you're problem, the above line is EXACTLY the same as the one before it. When the container parses through this JSP code it translates the above line to:
<p>$valittukurssi</p> on the WML page and the CLIENT uses it's local variable to display it.
What you need and want is to have a variable that can be used in JSP code and output to your WML page. Here's how it's done:
out.println("<go href='#helpcard'>");
String some_name = "valittukurssi";
out.println("<setvar name='"+some_name+"'
value='$("+some_name+")'/>");
//note that you may have to escape the ( and ) with a \
//so we displayed the variable above into the WML page, now we can use it in the SQL query:
/* SQL query with JSP */
ResultSet uudettulokset =
uusilause.executeQuery("select * from kurssi where
lyhenne='"+some_name+"'");//the end of the command is: " ' " ) ;
Frank Krul
Got Node? -
Having troubles passing values of Shuttle control to SQL Query of Report and Chart Region
Hello,
I am very new to APEX and need help for one of the Pa.I have a shuttle control on my page which populates Categories. Once user selects Categories from this control, I wish to pass the values to following SQL query :
select * from emp_class where category IN ( LIST of VALUES FROM RIGHT SIDE SHUTTLE).
I tried various ways of doing this including writing a java scripts which reads shuttle value, converts it into below string
'Category1',Category2',Category3'. Then I set this value to a text box. And then I was expecting that below trcik would work
select * from emp_class where category IN (:TXT_VALUES)
I am sure this is not right way and hence its not working. Can you please guide me here with options?
Many Thanks,
Tushb96402b4-56f7-44ba-8952-fb82a61eeb2c wrote:
Please update your forum profile with a real handle instead of "b96402b4-56f7-44ba-8952-fb82a61eeb2c".
I am very new to APEX and need help for one of the Pa.
Don't understand what this means. What is "Pa"?
select * from emp_class where category IN (:TXT_VALUES)
I am sure this is not right way and hence its not working. Can you please guide me here with options?
This is a common fallacy. In
select * from table where columnvalue in (7788, 7839, 7876)
(7788, 7839, 7876) is an expression list and the predicate is evaluated as a membership condition.
In
select * from table where columnvalue in :P1_X
:P1_X is a scalar string, incapable of containing multiple values.
In an APEX standard report, a PL/SQL function body returning an SQL query report source with lexical substitution can be used to produce a "varying IN-list":
return 'select * from table where columnvalue in (' || :P1_X || ')';
where P1_X contains fewer than 1000 values, has been sanitized for SQL injection, and string values are properly quoted.
Some people suggest the following approach, which will also work in APEX interactive reports:
select * from table where instr(':' || :P1_X || ':', ':' || columnvalue || ':') > 0
However this is non-performant as it eliminates the possibility of the optimizer using indexes or partition pruning in the execution plan.
See varying elements in IN list on Ask Tom, and emulating string-to-table functionality using sql for efficient solutions. -
Sql query with conditions and calculations???
Hi,
how I can build a query with conditions and calculations?
E.g. I've got this table
Start | End | Working Place | Mandatory
01-JAN-13 | 11-JAN-13 | Office | 1
14-JAN-13 | 25-JAN-13 | Home Office | 0
04-MRZ-13| 15-MRZ-13 | Office | 0
11-FEB-13 | 22-FEB-13 | Office | 1
Now if column working place=Office and column mandatory=0
the new column "price" has to calculate: (End-Start)* $25.00
and if working place=Office and column mandatory=1
the "price" column has to calculate: (End-Start)* $20.60
else $0.00
I tried it with the case statement but I didn't know how
to calculate my values and display it to the virtual column "price".
Something like
case
when Working_Place = 'Office' and Mandatory=1
then ...
else '0.00'
end as PRICE
Or is it not possible?
Edited by: DB2000 on 12.03.2013 05:09Use CASE:
select start_dt,
end_dt,
working_place,
mandatory,
case
when working_place = 'Office' and mandatory = 0 then (end_dt - start_dt) * 25
when working_place = 'Office' and mandatory = 1 then (end_dt - start_dt) * 20.60
else 0
end price
from tbl
START_DT END_DT WORKING_PLA MANDATORY PRICE
01-JAN-13 11-JAN-13 Office 1 206
14-JAN-13 25-JAN-13 Home Office 0 0
04-MAR-13 15-MAR-13 Office 0 275
11-FEB-13 22-FEB-13 Office 1 226.6
SQL> SY. -
I'm using the LabView Database Connectivity Toolset and am using the following query...
UPDATE IndexStation
SET Signal_Size=200
WHERE 'StartTime=12:05:23'
Now the problem is that this command seems to update all rows in the table IndexStation... Not just specifically the row where StartTime=12:05:23
I have tries all sorts of {} [] / ' " around certain characters and column names but it always seems to update all rows...
I've begun to use the SQL query tab in Access to try and narrow down as to why this happens, but no luck!
Any ideas!?
Thanks,
Chris.Chris Walter wrote:
I completely agree about the Microsoft issue.
But it seems no SQL based manual states that { } will provide a Date/Time constant.
Is this an NI only implementation? Because I can't seem to get it to function correctly within LabView or in any SQL query.
Chris.
There is nothing about the database toolkit in terms of SQL syntax that would be NI specific. The database Toolkit simply interfaces to MS ADO/DAO and the actual SQL syntax is usually implemented in the database driver or database itself although I wouldn't be surprised if ADO/DAO does at times munch a bit with that too.
The Database Toolkit definitely does not. So this might be a documentation error indeed. My understanding of SQL syntax is in fact rather limited so not sure which databases might use what delimiters to format date/time values. I know that SQL Server is rather tricky thanks to MS catering for the local date/time format in all their tools and the so called universal date/time format has borked on me on several occasions.
Rolf Kalbermatter
Rolf Kalbermatter
CIT Engineering Netherlands
a division of Test & Measurement Solutions -
How to query a table and result together with autonumber
Hi all
How to query a table and the result return autonumber for each row together with the table values.
I have tried rowid but it provide me with characters.
TjWhat is your exact requirement?
If you want the number of rows selected, you can use rownum.
select rownum, a.* from <table> a;
Cheers
Deepak -
Tuning SQL query with SDO and Contains?
I'trying to optimize a query
with a sdo_filter and an intermedia_contains
on a 3.000.000 records table,
the query look like this
SELECT COUNT(*) FROM professionnel WHERE mdsys.sdo_filter(professionnel.coor_cart,mdsys.sdo_geometry(2003, null, null,mdsys.sdo_elem_info_array(1,1003,4),mdsys.sdo_ordinate_array(809990,2087279,778784,2087279,794387,2102882)),'querytype=window') = 'TRUE' AND professionnel.code_rubr ='12 3 30' AND CONTAINS(professionnel.Ctx,'PLOMBERIE within Nom and ( RUE within Adresse1 )',1)>0
and it takes 15s on a bi 750 pentium III with
1.5Go of memory running under 8.1.6 linux.
What can i do to improve this query time?
nullHi Vincent,
We have patches for Oracle 8.1.6 Spatial
on NT and Solaris.
These patches include bug fixes and
performance enhancements.
We are in the process of making these patches
avaialble in a permanent place, but until then, I will temporarily put the patches on:
ftp://oracle-ftp.oracle.com/
Log in as anonymous and use your email for
password.
The patches are in /tmp/outgoing in:
NT816-000706.zip - NT patch
libordsdo.tar - Solaris patch
I recommend doing some analysis on
individual pieces of the query.
i.e. time the following:
1)
SELECT COUNT(*)
FROM professionnel
WHERE mdsys.sdo_filter(
professionnel.coor_cart,
mdsys.sdo_geometry(
2003, null, null,
mdsys.sdo_elem_info_array(1,1003,4),
mdsys.sdo_ordinate_array(
809990,2087279,
778784,2087279,
794387,2102882)),
'querytype=window') = 'TRUE';
2)
SELECT COUNT(*)
FROM professionnel
WHERE CONTAINS(professionnel.Ctx,
'PLOMBERIE within Nom and ( RUE within Adresse1)',1) >0;
You might want to try reorganizing the entire
query as follows (no promises).
If you contact me directly, I can try to
help to further tune the SQL.
Hope this helps. Thanks.
Dan
select count(*)
FROM
(SELECT /*+ no_merge */ rowid
FROM professionnel
WHERE mdsys.sdo_filter(
professionnel.coor_cart,
mdsys.sdo_geometry(
2003, null, null,
mdsys.sdo_elem_info_array(1,1003,4),
mdsys.sdo_ordinate_array(809990,2087279,
778784,2087279,
794387,2102882)),
'querytype=window') = 'TRUE'
) a,
(SELECT /*+ no_merge */ rowid
FROM professionnel
WHERE CONTAINS(professionnel.Ctx,
'PLOMBERIE within Nom and
( RUE within Adresse1)',1) >0
) b
where a.rowid = b.rowid
and professionnel.code_rubr ='12 3 30';
**NOTE** Try this with no index on code_rubr
null -
SQL Query with Distinct and Count is wrong.
Hello,
i have another problem with a query.
Here the Data:
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
CREATE TABLE TABLE_1
( "ORDER_NR" VARCHAR2 (12)
, "PRIORITY" VARCHAR2 (2)
, "WO_STATUS" VARCHAR2 (1)
, "STATUS_DATE" DATE
, "ART_NR" VARCHAR2 (9)
, "DESCRIPTION" VARCHAR2 (255)
, "PRICE" VARCHAR2 (10)
CREATE TABLE TABLE_2
( "ART_NR" VARCHAR(9)
, "MODELL" VARCHAR2(10)
, "MANUFACT" VARCHAR2(20)
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300612', '12', 'U', TO_DATE('05-FEB-13 10:22:39','DD-MON-RR HH24:MI:SS'), '005231987', '1ST ANNUAL SERVICE', '5000.2546');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300638', '05', 'U', TO_DATE('05-FEB-13 11:38:39','DD-MON-RR HH24:MI:SS'), '005667821', '3RD ANNUAL SERVICE', '5269.7856');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300638', '12', 'U', TO_DATE('06-FEB-13 12:38:39','DD-MON-RR HH24:MI:SS'), '005667821', '1ST BIENNIAL SERVICE', '1234.4468');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300638', '12', 'U', TO_DATE('07-FEB-13 13:38:39','DD-MON-RR HH24:MI:SS'), '005667821', '3RD ANNUAL SERVICE', '4366.7856');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300762', '12', 'U', TO_DATE('22-FEB-13 14:55:48','DD-MON-RR HH24:MI:SS'), '018743356', '3RD ANNUAL SERVICE', '4462.8632');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300766', '12', 'U', TO_DATE('22-FEB-13 08:32:13','DD-MON-RR HH24:MI:SS'), '018743356', '2ND ANNUAL SERVICE', '8762.6643');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300766', '05', 'U', TO_DATE('23-FEB-13 12:32:13','DD-MON-RR HH24:MI:SS'), '018743356', '1ST BIENNIAL SERVICE', '3425.6643');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300766', '12', 'U', TO_DATE('24-FEB-13 14:32:13','DD-MON-RR HH24:MI:SS'), '018743356', '2ND BIENNIAL SERVICE', '6678.6643');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300612', '12', 'U', TO_DATE('06-FEB-13 10:22:39','DD-MON-RR HH24:MI:SS'), '005231987', '1ST ANNUAL SERVICE', '5000.2546');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300638', '05', 'U', TO_DATE('05-FEB-13 11:38:39','DD-MON-RR HH24:MI:SS'), '005667821', '3RD ANNUAL SERVICE', '5269.7856');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300638', '12', 'U', TO_DATE('06-FEB-13 12:38:39','DD-MON-RR HH24:MI:SS'), '005667821', '1ST BIENNIAL SERVICE', '1234.4468');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300638', '12', 'U', TO_DATE('07-FEB-13 13:38:39','DD-MON-RR HH24:MI:SS'), '005667821', '3RD ANNUAL SERVICE', '4366.7856');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300762', '12', 'U', TO_DATE('22-FEB-13 14:55:48','DD-MON-RR HH24:MI:SS'), '018743356', '3RD ANNUAL SERVICE', '4462.8632');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300766', '12', 'U', TO_DATE('22-FEB-13 08:32:13','DD-MON-RR HH24:MI:SS'), '018743356', '2ND ANNUAL SERVICE', '8762.6643');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300766', '05', 'U', TO_DATE('23-FEB-13 12:32:13','DD-MON-RR HH24:MI:SS'), '018743356', '1ST BIENNIAL SERVICE', '3425.6643');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300766', '12', 'U', TO_DATE('24-FEB-13 14:32:13','DD-MON-RR HH24:MI:SS'), '018743356', '2ND BIENNIAL SERVICE', '6678.6643');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT1');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT2');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT3');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT4');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT5');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT6');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT1');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT2');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT3');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT4');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT1');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT2');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT3');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT4');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT5');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT6');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT1');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT2');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT3');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT4');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT5');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT6');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT1');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT2');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT3');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT4');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT1');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT2');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT3');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT4');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT5');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT6');
COMMIT;And my query:
SELECT T1.ART_NR
, T2.MODELL
, SUM(ROUND(T1.PRICE, 2)) AS TOTAL_PRICE
, COUNT(*) AS QTY
, TO_CHAR(T1.STATUS_DATE, 'MON-RR') AS MONTH
FROM TABLE_1 T1, TABLE_2 T2
WHERE T1.WO_STATUS = 'U'
AND T1.ART_NR = T2.ART_NR
AND TO_CHAR(T1.STATUS_DATE, 'MON-RR') = 'FEB-13'
GROUP BY T2.MODELL
, T1.ART_NR
, TO_CHAR(T1.STATUS_DATE, 'MON-RR')And the result:
ART_NR MODELL TOTAL_PRICE QTY MONTH
018743356 VACCUM 559916.16 96 FEB-13
005667821 LASER 173936.48 48 FEB-13
005231987 X-RAY1 120006 24 FEB-13My problem now is, the OTY field ist wrong it should count how often the equipment was in service in FEB-13 and group it by "MODELL" the MANUFACT field is not interesting for me, but this ist my problem, one Modell can have multible Manufacter and so i got a wrong count for my QTY.
The next step i need is to group the result also by Service type (annual or biennial), like this:
ART_NR MODELL TOTAL_PRICE QTY MONTH SERVICE_TYPE
018743356 VACCUM 1234.56 4 FEB-13 ANNUAL
018743356 VACCUM 4423.48 10 FEB-13 BIENNIAL
005667821 LASER 4783.11 2 FEB-13 ANNUAL
005667821 LASER 1123.77 22 FEB-13 BIENNIAL
005231987 X-RAY1 8966.12 6 FEB-13 ANNUAL
005231987 X-RAY1 7826.44 12 FEB-13 BIENNIALThis values are only out of my head, not the table, only to show what i need.
Thanks for your help.
Greets ReinhardHi,
Here's one way:
WITH got_groups AS
SELECT art_nr
, TRUNC (status_date, 'MONTH') AS month
, CASE
WHEN UPPER (description) LIKE '%ANNUAL%'
THEN 'ANNUAL'
WHEN UPPER (description) LIKE '%BIENNIAL%'
THEN 'BIENNIAL'
END AS service_type
, TO_NUMBER (price) AS price
FROM table_1
WHERE status_date >= DATE '2013-02-01'
AND status_date < DATE '2013-03-01'
, table_2_summary AS
SELECT DISTINCT art_nr, modell
FROM table_2
SELECT g.art_nr
, s.modell
, ROUND ( SUM (g.price)
, 2
) AS total_price
, COUNT (*) AS qty
, g.month
, service_type
FROM got_groups g
JOIN table_2_summary s ON s.art_nr = g.art_nr
GROUP BY g.art_nr
, s.modell
, g.month
, g.service_type
;The reason why your aggregates were originally too high is that you have a many-to-many relationship between the tables. The tables are related only by art_nr, but art_nr is not unique in either table. Look at art_nr '005231987', example. There ate 2 rows in table_1 with that art_nr, and 6 rows in table_2 with the same art_nr. If we join on art_nr, then both of the rows in table_1 will match each of the 6 rows in table_2, so the COUNT will be 2 * 6 = 12, and in the SUM, each of the numbers from table_1 will get added 6 times.
Why is table_2 designed the way it is? Cn there be multiple modells for the same art_nr? If so, what would you want for output? If there can only be 1 modell for each art_nr, then a better design would be to have a table that just had one row per art_nr, and included the modell column, and another table to show which manufacturers produce each art_nr. In this problem, you wouldn't need the manufacturers table, and the other table already has unique art_nrs, so you wouldn't need anything like the sub-query table_2_summary.
Don't store price in a VARCHAR2 column. Storing NUMBERs in a VARCHAR2 column is just asking for problems. Why not use a NUMBER column instead.
You'll notice that I used ROUND (SUM ... where you use SUM ( ROUND. The results might be a little different because of rounding errors. ROUND ( SUM only has to call ROUND once per group (5 times in this example) instead of once per row (16 times in this example). The less rounding you do, the less rounding error creeps in. Also, since there are fewer function calls, it's more convenient. (Of course, you'll never notice the difference between calling ROUND 5 times or 16 times, but in a real-life exampe, the difference could be between calling it 50 times or calling it 16000 times.) If you really need to use SUM (ROUND, you can. -
How to get the required output with single query to acheive IF SAL>2500 and job='manager' then display job as 'seniormanager'.
CREATE TABLE EMP(EMPNO NUMBER(4) NOT NULL,ENAME VARCHAR2(10),JOB VARCHAR2(9),MGR NUMBER(4),HIREDATE DATE,SAL NUMBER(7, 2),COMM NUMBER(7, 2),DEPTNO NUMBER(2));
INSERT INTO EMP VALUES(7521, 'WARD', 'SALESMAN', 7698,TO_DATE('22-FEB-1981', 'DD-MON-YYYY'), 1250, 500, 30);
INSERT INTO EMP VALUES(7566, 'JONES', 'MANAGER', 7839,TO_DATE('2-APR-1981', 'DD-MON-YYYY'), 2975, NULL, 20);
INSERT INTO EMP VALUES(7698, 'BLAKE', 'MANAGER', 7839,TO_DATE('1-MAY-1981', 'DD-MON-YYYY'), 2850, NULL, 30);
INSERT INTO EMP VALUES(7782, 'CLARK', 'MANAGER', 7839,TO_DATE('9-JUN-1981', 'DD-MON-YYYY'), 2450, NULL, 10);
INSERT INTO EMP VALUES(7788, 'SCOTT', 'ANALYST', 7566,TO_DATE('09-DEC-1982', 'DD-MON-YYYY'), 3000, NULL, 20);
IF SAL>2500 and job='manager' then display job as 'seniormanager'
SELECT * FROM EMP
expected output
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES SENIORMANAGER 7839 02-APR-81 2975 20
7698 BLAKE SENIORMANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20Hi,
The answer to "How do I ... using DECODE?", no matter how you fill in the blank, is "Don't use DECODE; use CASE instead." If you have to ask, then it's too complicated to do with DECODE.
Here's one way using CASE:
SELECT empno, ename
, CASE
WHEN job = 'MANAGER'
AND sal > 2500
THEN 'SENIORMANAGER'
ELSE job
END AS d_job
, mgr, hiredate, sal, comm, deptno
FROM emp
;If you really, really, really want to use DECODE:
SELECT empno, ename
, DECODE ( job
, 'MANAGER'
, DECODE ( SIGN (sal - 2500)
, 1
, 'SENIORMANAGER'
, job
, job
) AS d_job
, mgr, hiredate, sal, comm, deptno
FROM emp
;Nothing is literally too difficult to do in DECODE. Anything that case be done with CASE can also be done using DECODE, often using several times the amount of code. Bit which would you rther maintain: the CASE soltuion I posted first, of this DECODE soltuion. Which do you think will have more bugs? Which so you think will be faster? If you're using Oracle 8.1 (or higher) then don't use inefficient, high-maintenance code like this. Use CASE instead.
Edited by: Frank Kulash on Dec 26, 2012 3:27 PM
Added DECODE solution -
Learning SQL Query with JCheckBox and JButton
Hello,
I am learning how to access a very simple Access table. I am able to connect to the database and return a simple query. As I make it more complicated is where I have confused myself. The program is suppose to allow the user to pick any field they want to query using JCheckBox. After they have checked the fields off, the run query button is hit and outputs the results in a JOPtion Pane with a JTable. I am trying to do a test run and I can't make the query at least output something. If I can get any clues to the right direction would be appreciated. Thanks.
package mypackage25;
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class QueryAddressBook extends JFrame
private JLabel selectQueryLabel;
private JCheckBox firstName, lastName,
telephone, addressI, addressII, city,
state, zip;
private JPanel selectQueryPanel, checkBoxPanel, executePanel;
private JButton runQueryButton, clearSQLButton;
private Connection connection;
private Statement statement;
private ResultSet resultSet;
public QueryAddressBook()
super("Query an Address Book");
//Driver and Connection
try
//Driver for MicrosoftAccess
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//Inform the user that the Driver was loaded successfully
System.out.println("Driver Loaded");
//Connect to specific database(i.e. MyAddress3) in Access
Connection connection=DriverManager.getConnection("jdbc:odbc:MyAddress3");
//Inform User
System.out.println("Database connected");
}//end try
catch(ClassNotFoundException cnfe)
cnfe.printStackTrace();
}//end catch
catch(SQLException sqle)
sqle.printStackTrace();
}//end catch
//get content pane and set its layout
Container container=getContentPane();
container.setLayout(new BorderLayout());
//GUI Components
selectQueryLabel=new JLabel("Select Fields to be Queried");
firstName=new JCheckBox("First Name");
lastName=new JCheckBox("Last Name");
telephone=new JCheckBox("Telephone");
addressI=new JCheckBox("Address I");
addressII=new JCheckBox("Address II");
city=new JCheckBox("City");
state=new JCheckBox("State");
zip=new JCheckBox("Zipcode");
//register listeners for JCheckBoxes
CheckBoxHandler handler=new CheckBoxHandler();
firstName.addItemListener(handler);
lastName.addItemListener(handler);
telephone.addItemListener(handler);
addressI.addItemListener(handler);
addressII.addItemListener(handler);
city.addItemListener(handler);
state.addItemListener(handler);
zip.addItemListener(handler);
//set up selectQueryPanel
selectQueryPanel=new JPanel();
selectQueryPanel.setLayout(new FlowLayout());
selectQueryPanel.add(selectQueryLabel);
//set up CheckBox Panel
checkBoxPanel=new JPanel();
checkBoxPanel.setLayout(new FlowLayout());
checkBoxPanel.add(firstName);
checkBoxPanel.add(lastName);
checkBoxPanel.add(telephone);
checkBoxPanel.add(addressI);
checkBoxPanel.add(addressII);
checkBoxPanel.add(city);
checkBoxPanel.add(state);
checkBoxPanel.add(zip);
//set up execute panel
executePanel=new JPanel();
executePanel.setLayout(new FlowLayout());
//set up buttons
runQueryButton=new JButton("Run Query");
clearSQLButton=new JButton("Clear SQL");
runQueryButton.addActionListener
new ActionListener()
public void actionPerformed(ActionEvent event)
if(event.getSource().equals(runQueryButton))
runSQLQuery();
executePanel.add(runQueryButton);
executePanel.add(clearSQLButton);
container.add(selectQueryPanel, BorderLayout.NORTH);
container.add(checkBoxPanel, BorderLayout.CENTER);
container.add(executePanel, BorderLayout.SOUTH);
setSize(800,150);
setVisible(true);
public static void main(String args[])
QueryAddressBook dwgui=new QueryAddressBook();
dwgui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}//end main
//private inner class for ItemListener event handling
private class CheckBoxHandler implements ItemListener
public void itemStateChanged(ItemEvent event)
}//end method itemStateChanged
}//end private inner class CheckBoxHandler
private void runSQLQuery()
String output="";
try
statement=connection.createStatement();
resultSet=statement.executeQuery("select firstName from address");
while(resultSet.next())
output+=resultSet.getString(1)+"\n";
JOptionPane.showMessageDialog(null,output);
System.out.println(output);
}//end try
catch(SQLException sqle)
sqle.printStackTrace();
}//end catch
}//end runSQLQuery
}//end classAt present your query string is
"Select firstName from Address"
Instead of using the above hardcoded string, try to build the
query String using logic that checks which check boxes are selected
by the user.
Example..
String query = "SELECT ";
if (firstName.isSelected()) {
query = query + " firstName";
Be sure, you add the comma properly between two fields :-) -
SQL-Query - AR Invoice and related AR Down Payment Invoices
Hello everybody,
I want to show all AR Down Payment Invoices related to a given AR Invoice, i.e. a query approximately in this form:
SELECT
T0.DocNum AS 'Invoice',
T0.DocDate AS 'Invoice Date',
T0.DocTotal AS 'Open Amount',
T1.<<DocNum>> AS 'Down Payment Invoice',
T1.<<DocDate>> AS 'Down Payment Invoice Date',
T1.<<Amount>> AS 'Down Payment Invoice Amount'
FROM
OINV T0 INNER JOIN <<Down Payment Invoices>> T1
ON T0.DocEntry = T1.<<DocEntry>>
WHERE
T0.DocNum = xxxxx
I want to know if such a table <<Down Payment Invoices>> exists and what its name is.
Thanks for your help!
Regards,
Frank RomeniThanks for the INV11 - but this table seems to be empty even for invoices we have related down payments, e.g.
SELECT
T0.DocNum, T0.DocTotal, T1.<<whatever you want>>
FROM
OINV T0 LEFT OUTER JOIN INV11 T1
ON T0.DocEntry = T1.DocEntry
WHERE
T0.DocNum = xxxxx
That INV11 is always empty I could see with SELECT * FROM INV11
Regards
Frank Romeni
P.S.: I only post questions to this forum when I analysed my problems and only if I couldn't find any further information in the helpfiles. With regard to your first hint to ODPI there is no reference to INV11 in the helpfiles.
With regard to your comments I feel impelled to to say that if my question is confusing you, then it seems that nobody has ever taught you that meaning can be taken from the context. Regarding the "street", you asked me to find something: Do not waste your time with talking precociously ...
If you should feel annoyed by my comments, we'd better stop this conversation. Otherwise let us fall back to a strictly factual exchange of information, OK? I am not willing to discuss this any further!
F.R. -
SQL Query in C++ and Boost matrix libray
Hi all,
Suppose that one manages to query a series of 250 prices in c++ for 3 IDs such as:
ID1(1) | 1.0
ID1(250) |3.2
ID2(1) | 2.0
ID2(250)|4.0
ID3(1) |4.1
ID3(250) | 3.9
Does anyone know how to build a (250 * 3) price matrix for those IDs using Boost?
Any feedback would be very appreciated
Thanks a lotHi,
The description of your question is not clear and I am hard to get what you really want to do. Sorry about that.
Could you describe it more clearly ? it is better for me to help you solve your question.
In your statement, you may unclear how to use boost to create a metrix. It is a third party library, you should ask the question
on the office website of boost. And I can give you some suggestions.
First you should download boost and compile it.
Then you sould add to the additional include directories, like this:
Finally you could to learn how to use it on the boost office website. Here is the website:
http://www.boost.org/doc/libs/1_42_0/libs/numeric/ublas/doc/matrix.htm
and I have test the sample code in it and it works well.
Shu Hu
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Need help in framing an SQL query - Sample data and output required is mentioned.
Sample data :
ID Region State
1 a A1
2 b A1
3 c B1
4 d B1
Result should be :
State Region1 Region2
A1 a b
B1 c dcreate table #t (id int, region char(1),state char(2))
insert into #t values (1,'a','a1'),(2,'b','a1'),(3,'c','b1'),(4,'d','b1')
select state,
max(case when region in ('a','c') then region end) region1,
max(case when region in ('b','d') then region end) region2
from #t
group by state
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence
Maybe you are looking for
-
Installing Leopard freezes during installation..
hi. im updating my old tiger powermac to leopard and its freezing during installation.. i cant take the disc out and try the original discs as it seems like it needs the disc to boot from. ive held down the space bar but it doesnt eject. any ideas? t
-
when i am connecting ipod with laptop, an error is coming that "this ipod cannot be used because the apple mobile device services is not started??? please revert.
-
Clustered Durable MDB on Clustered JMS
Hi all we have an exception when trying deploy durable MDB in a cluster (WLS 7.0 SP3) the cluster have 2 instances. When we depploy Jar on cluster, the first MDB connect successfully, but on the other instances of cluster failed.
-
Version of SOA 10g - 11g SOA - BPM
Hello friends, How I can know the version of SOA and BPM that I have installed in my environment. Thanks
-
Videos on ipod don't appear in itunes
i put a couple video podcasts on my ipod and, while i can see them on my ipod, they don't show up when i connect it to my computer. i want to delete these files, but itunes doesn't recognize that there are any podcasts on my ipod. i've tried changing