Applying a calculation to a count in an sql query
Hi,
I have a query where I am producing the count of an id number in one column and then wish to output that count value *6 in the next column, how do I go about this.
SELECT HOUSE.CITY, COUNT(HOUSE.HOUSE_ID)"TOTAL LESS", COUNT(HOUSE.HOUSE_ID)"HOUSE TOTAL", COUNT(HOUSE.HOUSE_ID)*6 HOUSE VALUE
FROM HOUSE
Thanks for your ideas
Just the way you think:
WITH t AS
(SELECT 'House1' var1 FROM DUAL
UNION
SELECT 'House2' var1 FROM DUAL
UNION
SELECT 'House3' var1 FROM DUAL)
SELECT COUNT (var1) num, COUNT (var1) * 6 num6
FROM t
NUM NUM6
3 18
1 row selected.I think your problem is the missing quotes around HOUSE VALUE.
a
Similar Messages
-
JDBC:Count Array. SQL query works but fails in JDBC
Hi,
I'm using the following SQL query
"SELECT red.id, name, count(green.id) FROM red, green WHERE area = 'northeast' AND red.id = zid GROUP BY name"
It executes perfectly from the DB command line giving me the results.
However when I call it from within JDBC i am getting null values.
My JDBC call ia as follows( Where lst is the above query)
rs = st.executeQuery(lst);
while(rs.next()){
nidV.addElement(rs.getString("red.id"));
nnmV.addElement(rs.getString("name"));
nnumV.addElement(rs.getString("count(green.id)"));
I do realize that many folks use Integer for count queries but I pull them with as Strings all the time so that's not it.
The one diffrence between this and my other count queries is that this one returns an array (Vector) of counts.
Any ideas?the problem is probably:
SELECT red.id, name, count(green.id) ...
nnumV.addElement(rs.getString("count(green.id)"));you can either use an alias for the column;
SELECT red.id, name, count(green.id) COUNT_VAR
nnumV.addElement(rs.getObject("COUNT_VAR"));or use getObject(3) as suggested by drclap. -
How to get row count of a sql query
After firing a query, how can i get the number of records returned by the query from the database, it should be database indipendent.
Statement stmt = conn.createStatement();
stmt.executeQuery(query);After this I want the number of row i.e. the number of records returned by the database.Number of rows in a ResultSet may be obtained with:
ResultSet rs;
int numRows=rs.last().getRow();
I would have said this too, as a matter of fact I mentioned scrollable result sets in my post, but as I said, not all drivers support this, and he said he needed it to be database independent, so this method should not be used. -
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 write SQL query and apply aggregate functions on it
Hello experts,
Iu2019ve a task to write SQL query on tree tables and do inner join on them. Iu2019ve accomplish this task by using T-CODE SQVI. However now I need to write a query and apply SQL functions on it i.e. Add, Count, Max and Min etc. Please can someone tell me how I can write SQL query with aggregate functions in SAP?
Thanks a lot in advanceHI Mr. Cool
you can see the below code for using aggregate functions.
where ARTIST and SEATSOCCU are the field names for which you want to perform these functions.
DATA: TOTAL_ENTRIES TYPE I,
TOTAL_ATT TYPE I,
MAX_ATT TYPE I,
AVG_ATT TYPE I.
SELECT COUNT( DISTINCT ARTIST )
SUM( SEATSOCCU )
MAX( SEATSOCCU )
AVG( SEATSOCCU ) FROM YCONCERT INTO (TOTAL_ENTRIES, TOTAL_ATT,
MAX_ATT, AVG_ATT).
Thanks
Lalit Gupta -
Showing column value as counter in sql query - report
I created a classic report with search bar based on an sql query. I would like to show the "notes" column in this query using some sort of counter and as a hyperlink to another section on the page (same idea as footnotes in a book). So if I have 10 rows and 5 have "notes". I should show 1,2,3,4,5 in the notes column for those rows and the number gets displayed as a link to another section listing the notes 1 through 5.
I was thinking of creating a hidden page item as the counter with value of 0 and then in my query doing counter+1 but i'm not sure how to do this or if i can do that...
If anyone can help or have any other ideas I would really appreciate it!!
Thanks,
HindyWell, I'm doing this in VB and the subquery is dynamic. I'm passing an ADO recordset to a routine that sets up a listview to display the results. The number of columns selected can vary. My idea was to size the columns appropriately based on the size of the data. Within the display routine I could:
sql = "SELECT "
for i = 0 to oRS.Fields.Count - 1
sql = sql & "MAX(LENGTH(" & i & ")), "
next 'i
sql = sql & "FROM (" & oRS.Source & ")" -
How to create a counter using Oracle SQL Developer?
Is there any way to create a counter using Oracle SQL Developer to create the below scenario. Meaning it will recorded down the name of user and ID and time and the date they login.
Library portal home statistics shows how many users (outside and within the campus) visit the library portal.
Page Access statistics is recorded on an hourly basis. Users may select the statistics by
yearly (statistics displayed by all months in the selected year)
monthly (statistics displayed by all days in the selected month)
daily (statistics displayed by all hours in the selected day)I'm giving here one basic post - hope this will solve your problem --
SQL>
SQL>
SQL> create table audit_info
2 (
3 usr varchar2(50),
4 log_time timestamp(6)
5 );
Table created.
SQL>
SQL>
SQL> create table err_log
2 (
3 log_cd varchar2(20),
4 log_desc varchar2(500)
5 );
Table created.
SQL>
SQL>
SQL> create or replace procedure ins_err(errcd in varchar2,
2 errnm in varchar2)
3 is
4 pragma autonomous_transaction;
5 begin
6 insert into err_log values(errcd,errnm);
7 commit;
8 end;
9 /
Procedure created.
SQL>
SQL>
SQL> create or replace procedure ins_aud(ud in varchar2,
2 unm in varchar2)
3 is
4 pragma autonomous_transaction;
5 begin
6 insert into audit_info values(ud,unm);
7 commit;
8 exception
9 when others then
10 ins_err(sqlcode,sqlerrm);
11 end;
12 /
Procedure created.
SQL>
SQL>
SQL>
SQL> create or replace trigger log_odsuser1
2 after logon on odsuser1.schema
3 begin
4 ins_aud('ODSUSER1',sysdate);
5 exception
6 when others then
7 ins_err(sqlcode,sqlerrm);
8 end;
9 /
Trigger created.
SQL>
SQL*Plus: Release 9.2.0.1.0 - Production on Tue Jun 12 12:21:09 2007
Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
Connected to:
Oracle9i Enterprise Edition Release 9.2.0.6.0 - 64bit Production
With the Partitioning, OLAP and Oracle Data Mining options
JServer Release 9.2.0.6.0 - Production
SQL>
SQL>
SQL>
SQL> set serveroutput on
SQL>
SQL>
SQL> select * from audit_info;
USR
LOG_TIME
ODSUSER1
12-JUN-07 12.00.00.00000000 AMHope this will solve your purpose.
Regards.
Satyaki De. -
Is there a way to consolidate calculations used in SQL Query Data Sets?
I am building SQL Query Data Sets against multiple DB Views which all have different date formats. I have the date parameter working well, but want to consolidate the changes that I have to do to it especially for the quarter. For example the SQL against a monthly view would use "where year_month > to_char(:ST_DATE, 'YYYY-MM')" which is not too hard, but to make that work for the quarterly view I need several concats and a decode to get a "> '2012-Q2'". I would like not to have to do this within every where clause. I had put this into a global element hoping to use that in a filter for the data set, but the filter does not have access to global elements only parameters.
Is there any way to refer to a calculated global element from the data set to do this? I am using Layout Templates, so even if I wanted to I could not do the condition within the template.
Thanks,
RickChange the following line to include the red coloured parts
<div class="MasterColumn" spry:repeat="ds4" spry:setrow="ds4" spry:hover="MasterColumnHover" spry:select="MasterColumnSelected">
<span>{Dsp_#}</span><span>{Dsp_WkDay}</span><span>{Dsp_Event}</span>
</div>
The add the following style rule to your document:
.MasterColumn span {
display: inline-block;
I hope this helps.
Ben -
SQL query not calculating
gross_amount is giving the value of extended_amount and the gross_price_rc is giving the value of unit_selling_price
select customer_trx_line_id,
( extended_amount / 1- (decode(decode(attribute6,null,0)+decode(attribute7,null,0)+decode(attribute8,null,0)+decode(attribute9,null,0)/100,null,0,1,0))) GROSS_AMOUNT,
( unit_selling_price /1-(decode(decode(attribute6,null,0)+decode(attribute7,null,0)+decode(attribute8,null,0)+decode(attribute9,null,0)/100,null,0,1,0))) gross_price_rc
from ra_customer_trx_lines_all
where attribute6 is not null or attribute7 is not null or attribute8 is not null or attribute9 is not null
whats the isuue here??
Thanksdecode(attribute7,null,0)Looking at it again, this always returns 0 or NULL, so it not really surprising
DECODE
http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions040.htm#i1017437
CASE
http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/expressions004.htm#i1033392 -
How to get the table_name and its count(*) in a SQL
Hi,
Can anybody tell me how to write a sql to get the table_name and its count(*) in a SQL:
Output should be:
table_name count(*)
XXX 261723
YYY 3343
Regards,
G. Rajakumar.hello
there r a lot ways
i'll suggest u two of them
1) the following dynamic sql procedure
DECLARE
TYPE array_type IS TABLE OF VARCHAR(30);
TYPE cur_typ IS REF CURSOR;
c1 cur_typ;
count1 integer;
tab_arr array_type;
querystr varchar2(200);
begin
SELECT table_name bulk collect into tab_arr FROM sys.all_all_tables ;
FOR I IN tab_arr.first..tab_arr.last LOOP
DBMS_OUTPUT.PUT(TAB_ARR(I));
querystr := 'select count(*) from ' ||TAB_ARR(I);
open c1 for querystr;
fetch c1 into count1;
EXIT WHEN c1%NOTFOUND;
dbms_output.put_line(count1);
END LOOP;
close c1;
END;
2) or use ANALYZE to analyze the tables and get the number of rows in the NUM_ROW column of DBA_TABLES view.
if u still have any problem mail me at [email protected]
shalini -
SQL query to count number of VMs
In OVM 2.2 I could run a SQL query against the OVM database to count the number of VMs that I had created, for automated reporting purposes.
I've looked at the 3.1 OVM database and it looks like most of the data is kept in BLOB columns. So does anyone know how I might query the 3.1 database to count the number of VMs?
Thanks.Hi,
Combine the relevant data from the three tables (using UNION ALL) in a sub-query. without the GROUP BY.
Your main query can select from the sub-query's result set, as if it were a table. Do the GROUP BY in the main query.
That is:
WITH u AS
SELECT TO_CHAR (emp_start, 'YYYY') AS yr FROM Adminstaff
UNION ALL
SELECT TO_CHAR (emp_start, 'YYYY') AS yr FROM Clerk
UNION ALL
SELECT TO_CHAR (emp_start, 'YYYY') AS yr FROM ITstaff
SELECT COUNT (*) AS cnt
, yr
FROM u
GROUP BY yr
ORDER BY cnt DESC
;Since empno is the primary key, it's easier not to mention empno at all in the sub-query, and use "COUNT (*)" instead of "COUNT (empno)" in the main query. The results are the same.
It might be a little more efficient to GROUP BY in all three branches of the sub-query, and then to SUM the results in another GROUP BY in the main query. That means more code, of course, which I'll leave as an exercise for you.
Why do you have three separate tables? I can understand that nobody else wants to be near the IT Staff, but it seems like lots of things (including this job) would be a lot simpler if all employees were all in one table, with a column to designate to which group (Adminstaff, Clerk or ITStaff) each one belongs. -
Hi in my sql query i applied like condition (like '%TEST') but it is taking long time. I applied indexes also,but still i'm facing the same problem. In my databse nearly 2,00,000 records their.
Hi Manikandan
Is there a difference in performance between running the query in BEx and WebI?
have you aggregates in place on the BEx side of things?
When you say its taking too long to open the report, have you a variable screen coming up for the report and is that what is taking the time or is it the report execution.
With regards
Gill -
Sql query to get distinct count
Hi
I use SQL Server Management Studio
can I have a sql query to get count as shown below against each month column and name column to get distinct count.
for example if there is two rows with the same date period and same name then the count should be one in first row and zero in the next row of the same data.
Table Name: Table1
Column: Month, Name
Month
Name
Count
12/1/2012 0:00
AK
1
12/1/2012 0:00
AK
0
12/1/2012 0:00
AB
1
1/1/2013 0:00
AK
1
1/1/2013 0:00
AK
0
1/1/2013 0:00
AB
1
3/1/2013 0:00
AA
1
3/1/2013 0:00
AK
1
3/1/2013 0:00
AK
0
6/1/2013 0:00
AA
1
6/1/2013 0:00
AK
1
6/1/2013 0:00
AK
0
9/1/2013 0:00
AA
1
9/1/2013 0:00
AK
1
9/13/2013 0:00
AK
1
10/1/2013 0:00
AA
1
10/1/2013 0:00
AK
1
10/1/2013 0:00
AK
0Hi,
Thanks for the query but this query gives the total count like shown below
if see the second row in the below table AK for 2012-12-1 gives total count as 2 but need the query to show the first row as 1 and there after 0
query result
Month name cnt
2012-12-01 00:00:00.000 AB 1
2012-12-01 00:00:00.000 AK 2
2012-12-01 00:00:00.000 AK 2
2013-01-01 00:00:00.000 AB 1
2013-01-01 00:00:00.000 AK 2
2013-01-01 00:00:00.000 AK 2
2013-03-01 00:00:00.000 AA 1
2013-03-01 00:00:00.000 AK 2
2013-03-01 00:00:00.000 AK 2
2013-06-01 00:00:00.000 AA 1
2013-06-01 00:00:00.000 AK 2
2013-06-01 00:00:00.000 AK 2
2013-09-01 00:00:00.000 AA 1
2013-09-01 00:00:00.000 AK 1
2013-09-13 00:00:00.000 AK 1
2013-10-01 00:00:00.000 AA 1
2013-10-01 00:00:00.000 AK 2
2013-10-01 00:00:00.000 AK 2 -
SQL Query - SCOM2012R2 Performance Counter
Need some assistance with a SQL query against my SCOM DW. I want this to do a select within a select. The inner select must collect the raw data for a performance counter, for the last 5 minutes. But SCOM will only give me counters that collected in the
last 5 minutes. What i want is the last value for every managed instance. - 1500 servers.
The outer SELECT must then filter this by doing a count on how many servers it collected a value for that are above 80% - and then divide that number by the total managed servers to give me a percentage of servers above 80% memory used. Eg - it counts 10
servers are above 80%, but theres 100 servers - then gives me a final figure of 90%.
select (count(abc.DaValue)) from (
select
vManagedEntity.Path
,vPerformanceRule.ObjectName
,vPerformanceRule.CounterName
,AVG(vPerfRaw.SampleValue) AS DaValue
from vPerfRaw
join vPerformanceRuleInstance on vPerformanceRuleInstance.PerformanceRuleInstanceRowid = vPerfRaw.PerformanceRuleInstanceRowid
join vPerformanceRule on vPerformanceRule.RuleRowId = vPerformanceRuleInstance.RuleRowId
join vManagedEntity on vManagedEntity.ManagedEntityRowid = vPerfRaw.ManagedEntityRowId
where vPerfRaw.Datetime > DATEADD(minute, -20, GETUTCDATE())
and vPerformanceRule.ObjectName = 'Memory'
and vPerformanceRule.CounterName = 'PercentMemoryUsed'
GROUP BY Path, ObjectName, CounterName, Name
Order by DaValue DESC)
as abc
where abc.DaValue >= 80
This statement gives me the result
Msg 1033, Level 15, State 1, Line 15
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
Any ideas ?Latest update -
SELECT count(DISTINCT abc.server) as NoOfServers,
count(case when abc.DaValue >= 90 then abc.DaValue end) 'MemoryAbove90%'
FROM( select TOP 100 PERCENT
vManagedEntity.Path as Server ,vPerformanceRule.ObjectName
,vPerformanceRule.CounterName ,AVG(vPerfRaw.SampleValue) AS DaValue
from Perf.vPerfRaw join vPerformanceRuleInstance on vPerformanceRuleInstance.PerformanceRuleInstanceRowid = vPerfRaw.PerformanceRuleInstanceRowid
join vPerformanceRule on vPerformanceRule.RuleRowId = vPerformanceRuleInstance.RuleRowId
join vManagedEntity on vManagedEntity.ManagedEntityRowid = vPerfRaw.ManagedEntityRowId
where vPerfRaw.Datetime > DATEADD(minute, -10, GETUTCDATE())
and vPerformanceRule.ObjectName = 'Memory' and vPerformanceRule.CounterName = 'PercentMemoryUsed'
GROUP BY Path, ObjectName, CounterName, Name
Order by DaValue DESC) as abc
This gives me Total Servers collected from, and Total Servers found to have AVG collections over 90% for Memory Util.
My KPI states that I must only display the number of servers that are above 90%, for more than 10minutes.
The problem with this is that when i run it over a 10 minute period, I get collections for about 40% of my managed servers only.
I want to know if anyone has a better way of collecting the perf data over a 10 minute period ?
What i was thinking of doing is running this query with time interval on 11 minutes, populating a temp table with the data, running the query
again with time interval on 1 minute ago, and comparing the results. IF it finds a match, I know that the server has been over 90% memory util for 10 minutes - then i can count it ? Its probably not entirely accurate, but Im out of ideas. From here, i want
to export the Values for Total Servers and TotalServersAbove90% into Excel, and build a guage off it that will reflect a % of Servers within SLA -Memory Util.
Im not entirely familiar with SCOM collection intervals, IF I run the query for the last 1 minute - It seems to skip alot of servers and only returns
data from about 50, is that because its not cycling on those at that moment ? In which case my idea above wont work.
UPDATE 2 - i think this will do it
Our OPS guy just told me that we sample every 10min. So immediately im thinking, perhaps i can run the query for the last 11 minutes - IF more than
1 sample is above 90%, the server is above 90% for more than 10min.
But, when i run this query
select TOP 100 Percent Path, AVG(SampleValue) AS Value, DateTime from Perf.vPerfRaw pvpr inner join vManagedEntity vme on pvpr.ManagedEntityRowId
= vme.ManagedEntityRowId inner join vPerformanceRuleInstance vpri on pvpr.PerformanceRuleInstanceRowId = vpri.PerformanceRuleInstanceRowId inner join vPerformanceRule vpr on vpr.RuleRowId = vpri.RuleRowId WHERE ObjectName = 'Memory' AND CounterName
= 'PercentMemoryUSed' AND Datetime > DATEADD(minute, -1, GETUTCDATE()) AND SampleValue >= 90 GROUP BY Path, SampleValue, DateTime ORDER BY DateTime DESC
I get a few servers, but some have more than 1 entry in the last 1 minute. Which means that i cant compare 2 samples.
Perhaps i could say if ALL samples collected per server in that 11 minute period are > 90,
then add 1 to MemoryAbove90% -
Creating a ad-hoc calculation using sql query
Hi All,
I want to know if its possible some way to create a ad-hoc sql query inside a workbook so as to create a calculation using that sql.
I have a folder which gives me balance for any period. My requirement is to display current period balance along with prior years closing balance in same record for each code combination. I dont want to modify folder definition.
Thanks for your inputs.
Vishal.You could try creating a custom function for this purpose. You would need to register the function in the End User Layer and then you can call the function from your report.
Maybe you are looking for
-
SOLUTION: Windows Vista + iPod Shuffle 2nd Gen
My original question on this topic is closed, but I finally fixed the problem and wanted to share. The problem was: Windows Vista Basic desktop machine and iTunes would recognize a Video iPod, but not recognize an iPod second generation Shuffle The s
-
Macbook pro 13inch running slow and losing connection (had it for only a year)
Will someone please help me.. I've only had my mac book pro for a year only and few months ago I started experiencing that my macbook has been running slow lately.. I still have alot of memory in it because I only use it for browsing the net and savi
-
How to set an alert for unauthorized ClearPass login
Q: As a network administrator, how do i set alerts for a unauthorized access to ClearPass server (via SMS or Mail) ? A: A network admin would want to know, if someone unauthorized is trying to access the ClearPass server. The solution below explains,
-
AE 5.2: No records Found
Hi, After importing the roles from SAP ECC backend system, i tried creating a request. While i tried to search for the roles while creating a request, it says " No Records found". I checked in the Config Tab in AE under Roles, I could see the roles i
-
Iphoto Library: Data Folder versus Originals Folder
Hi. I've been trying to save some space. I realized that I have the same photo stored in 3 different folders: my personal file folder (from where I imported), and within the "iphoto library" in 2 different folders: Originals and Data Folder. I got ri