Two count(*) in sql statement
hi viewers,
I need the similar query in oracle for the following Informix query.
select count(*),(select count(*) from table_name where col1=10) from table_name where col1=10;
i have a solution also but the problem is, if that table has no rows then output is not 0,0
select count(*),(select count(*) from table_name where col1=10) from table_name where col1=10 group by col1;
thanks
hari
A little remark: the behavoiur you stick on is a default feature in Oracle:
SQL> select count(*) from emp where deptno = 40;
COUNT(*)
0
SQL> select count(*) from emp where deptno = 40 group by deptno;
no rows selectedThese two queries work differ. It is described in Oracle documentation:
http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions001.htm#i89203
Oracle applies the aggregate functions to each group of rows and returns a single result row for each group.
If you omit the GROUP BY clause, then Oracle applies aggregate functions in the select list to all the rows in the queried table or view
As Alex pointed out, you should not include group by clause and should use count(*) instead of a subquery.
Rgds.
Similar Messages
-
Select count(*) on sql statement returning zero when a matching row exists.
Our account has an ANSI C application that checks for the existence a row on an Oracle table(s) by using the following SQL:
int iCount = 0;
EXEC SQL
SELECT count(rownum) INTO :iCount
FROM sys.all_tab_columns
WHERE table_name IN
(SELECT table_name FROM
sys.all_synonyms
WHERE upper(synonym_name) = upper(:szDestTable))
AND upper(column_name) = upper(:szColumnName)
AND owner = 'DBAUSER';
The bind variables szDestTable and szColumnName are populated with values parsed from columns on another database table. This application is executed through out the day. Occasionally, the application will report a zero in the iCount when there should be a match. I have verified the szDestTable and szColumnName are populated with the correct values which would find a match and they are correct. To make matters even stranger, the application will parse the same input values and find a match (as it should). At some point during the day, and it can be at any time, the application will NOT find a match on the same file, same values. Every subsequent execution of this application will not find a match on the same values. Once the database is brought down and started up in the evening for its normal backups, the application will find a match again on the same values. This problem does not occur every day. I could be a week or a week and a half between incidents.
I printed the contents of the sqlca.sqqlerrm.sqlerrmc field to a log file. The sqlca.sqlerrm.sqlerrmc field reported an ORA-1405 bind variable was null when the iCount was reporting a zero. When I compiled this application, I set the Proc*C flag to UNSAFE_NULLS=yes since there are other bind variable in the application that can be NULL and that is ok.
The above SQL is compiled into the C application using the Proc*C compiler. It is compiled using the Oracle 11.2.0.2 libraries. The application is executed against an Oracle 11.2.0.2 database. The database and application are executed on an HP/Unix 11.31 platform.
This problem did not start occurring until our account went from Oracle 10.2 to Oracle 11.2. Recently, I have changed the SQL to perform a “SELECT COUNT(rownum)” instead of the “SELECT COUNT(*)”. I compiled the application and executed the new application with the SELECT COUNT(rownum) against the same database where the same application with the SELECT COUNT(*) was failing to find a row that actually existed. The application with the SELECT COUNT(rownum) found the matching row as it should have. The new application has been executing in production for about 10 days now without any problems against ten various Oracle 11.2 databases.
Why would SELECT COUNT(*) and SELECT COUNT(rownum) be any different?This forum is about C programming in general, and about using Studio C in particular.
Your question is about Oracle database programming. You are more likely to find a helpful answer in a forum about database programming. Start here:
https://forums.oracle.com/forums/category.jspa?categoryID=18 -
Help Using Count and SQL statements
Hello
This problem has been bugging me incesantly and I would be reaaaaaaally grateful if someone could help here
I want to create query that woud count the number of times a certain unedited word would be matched against different edited words
This query works well in MS ACCess but not in java
query =" SELECT Count(*) AS WordCount, Segmentations.EditedWord FROM [select Segmentations.EditedWord FROM Segmentations where Segmentations.UneditedWord = '"+Word+"']. AS c GROUP BY Segmentations.EditedWord";
I've tried removing the Segmentations. and changing it to
query =" SELECT Count(*) AS WordCount, EditedWord FROM [select EditedWord FROM Segmentations where UneditedWord = '"+Word+"']. AS c GROUP BY EditedWord";
But still nothing
I think that is due to the fact that you can't call Count(*) and another field at the same time
pleas eif anyone knows a way around this send it ASAP
thanxWhy not use,
query = "SELECT Count(*) AS WordCount, EditedWord FROM Segmentations WHERE UneditedWord = ? GROUP BY EditedWord"and use PreparedStatement to optimize.
HTH -
I'm trying to do two fairly tricky SQL statements for a class, and been trying for a while and have gotten stuck.
The first one is, "Find Courses where more than half the students got an A"
I've basically been trying to use not exist statements to set it up and then compared the count(sid)/2 > count(sid) query of all A's and am just not getting decent results from it.
The REALLY tricky one is "Find the pairs of students who took exactly the same set of courses"
I can get a cross product from all students with something like this
SELECT s1.sname, s2.sname
FROM lab6_student s1, lab6_student s2
WHERE s1.sname > s2.sname
but after that I can't seem to get it to work properly at all.
Thanks for any pointers/advice!1.
SQL> WITH T
2 AS (SELECT 'mathematics' course_name, 'john' student_name, 'A' grade FROM DUAL
3 UNION ALL
4 SELECT 'mathematics' course_name, 'john1' student_name, 'A' grade FROM DUAL
5 UNION ALL
6 SELECT 'mathematics' course_name, 'john2' student_name, 'A' grade FROM DUAL
7 UNION ALL
8 SELECT 'mathematics' course_name, 'john3' student_name, 'B' grade FROM DUAL
9 UNION ALL
10 SELECT 'physics' course_name, 'john' student_name, 'A' grade FROM DUAL
11 UNION ALL
12 SELECT 'physics' course_name, 'john1' student_name, 'B' grade FROM DUAL
13 UNION ALL
14 SELECT 'physics' course_name, 'john2' student_name, 'B' grade FROM DUAL
15 UNION ALL
16 SELECT 'physics' course_name, 'john3' student_name, 'B' grade FROM DUAL)
17 SELECT *
18 FROM T;
COURSE_NAME STUDE G
mathematics john A
mathematics john1 A
mathematics john2 A
mathematics john3 B
physics john A
physics john1 B
physics john2 B
physics john3 B
8 rows selected.
SQL> WITH T
2 AS (SELECT 'mathematics' course_name, 'john' student_name, 'A' grade FROM DUAL
3 UNION ALL
4 SELECT 'mathematics' course_name, 'john1' student_name, 'A' grade FROM DUAL
5 UNION ALL
6 SELECT 'mathematics' course_name, 'john2' student_name, 'A' grade FROM DUAL
7 UNION ALL
8 SELECT 'mathematics' course_name, 'john3' student_name, 'B' grade FROM DUAL
9 UNION ALL
10 SELECT 'physics' course_name, 'john' student_name, 'A' grade FROM DUAL
11 UNION ALL
12 SELECT 'physics' course_name, 'john1' student_name, 'B' grade FROM DUAL
13 UNION ALL
14 SELECT 'physics' course_name, 'john2' student_name, 'B' grade FROM DUAL
15 UNION ALL
16 SELECT 'physics' course_name, 'john3' student_name, 'B' grade FROM DUAL)
17 SELECT *
18 FROM (SELECT course_name, COUNT (*) total_cnt, SUM (CASE WHEN grade = 'A' THEN 1 ELSE 0 END) grade_cnt
19 FROM T
20 GROUP BY course_name)
21 WHERE grade_cnt > total_cnt / 2;
COURSE_NAME TOTAL_CNT GRADE_CNT
mathematics 4 3
SQL>
2.
SQL> WITH T
2 AS (SELECT '1' course_id, 'john' student_name FROM DUAL
3 UNION ALL
4 SELECT '2' course_id, 'john' student_name FROM DUAL
5 UNION ALL
6 SELECT '1' course_id, 'peter' student_name FROM DUAL
7 UNION ALL
8 SELECT '2' course_id, 'peter' student_name FROM DUAL
9 UNION ALL
10 SELECT '3' course_id, 'king' student_name FROM DUAL
11 UNION ALL
12 SELECT '4' course_id, 'king' student_name FROM DUAL)
13 SELECT *
14 FROM t;
C STUDE
1 john
2 john
1 peter
2 peter
3 king
4 king
6 rows selected.
SQL> WITH T
2 AS (SELECT '1' course_id, 'john' student_name FROM DUAL
3 UNION ALL
4 SELECT '2' course_id, 'john' student_name FROM DUAL
5 UNION ALL
6 SELECT '1' course_id, 'peter' student_name FROM DUAL
7 UNION ALL
8 SELECT '2' course_id, 'peter' student_name FROM DUAL
9 UNION ALL
10 SELECT '3' course_id, 'king' student_name FROM DUAL
11 UNION ALL
12 SELECT '4' course_id, 'king' student_name FROM DUAL),
13 r
14 AS (SELECT student_name, SUM (POWER ( 2, course_id)) val
15 FROM T
16 GROUP BY student_name)
17 SELECT DISTINCT student_name NAME
18 FROM r
19 WHERE EXISTS
20 (SELECT 'x'
21 FROM r r1
22 WHERE r1.val = r.val
23 GROUP BY val
24 HAVING COUNT (*) > 1);
NAME
john
peterEdited by: G. on Feb 24, 2011 2:09 PM -
Sender JDBC adapter : Update SQL Statement : stored procedure
Hi,
Can we use a stored procedure in the sender jdbc adapter in 'Update SQL Statement'.
The problem i am facing is like, we are selecting data from two tables in 'SQL statement for query' and then in 'Update SQL Statement' , we need to delete that data from these two tables.
Please let me know if it is possible.
Thanks,
Rohityou can use a Stored procedure in the
Query SQL Statement
You have the following options:
· Specify a valid SQL SELECT statement to select the data to be sent from the specified database.
· Specify an SQL EXECUTE statement to execute a stored procedure, which contains exactly one SELECT statement.
The expression must correspond to the SQL variant supported by the relevant JDBC driver. It can also contain table JOINs.
so have your whole select and update as part of this single Stored procedure -
How to SUM two count(*) values in a single sql tatement?
How can I get a single SQL statement to sum two values from a count(*)
I want something like this:
SELECT COUNT(*) FROM MYTABLE
UNION
SELECT COUNT(*) FROM MYOTHERTABLE;
but instead of getting
111
222
I want to see the sum of the two values.
333can such a thing be done with one statement. I know I can do stuff inside a BEGIN END and have vars but wonder if there is simple single statement solution.
Thanks in advance,
David MillerSQL> select count(*) from user_indexes;
COUNT(*)
30
SQL> select count(*) from user_tables;
COUNT(*)
43
SQL> select (select count(*) from user_indexes) + (select count(*) from user_tables)
2 from dual;
(SELECTCOUNT(*)FROMUSER_INDEXES)+(SELECTCOUNT(*)FROMUSER_TABLES)
73 -
SQL statement with LIMIT and total count?
Hello,
I would like to know if it is possible to execute a single SQL statement that will return me a subset of data (for pagination purposes) that not only includes the subset of data for the page but the count of all available data. Can this be done so as to not take up the cpu and time it takes to essentially run two queries? One to get the subset and one to get the count? I think simply doing a subselect is not going to give me what I want in that we actually query twice.
There may be no way to do this other than that, but I wanted to check with the gurus here first. :)
Thanks,
Markselect *
from (
select i.*,
row_number() over(order by i) rn, -- used for
pagination
count(*) over(partition by 1) cnt -- total count
of rows found for this search
from mytable
where < PUT ALL LIMITING (i.e., "search") CONDITIONS
HERE >
where rn between 41 and 50 -- pagination clauseNice one
BUT of course it adds additional row in execution plan and takes additional time and CPU :)
I assume that it directly depends of course on returned result set and some other factors like available sort space but a simple test case on a table big which actually is 1.6 M rows like dba_source got following results:
here is the first one returning also count(*)
SQL> select *
2 from (
3 select i.*,
4 row_number() over(order by owner, name, type) rn
5 , -- used for pagination
6 count(*) over(partition by 1) cnt -- total count of rows found for this search
7 from big i
8 where owner like 'S%' and name like '%A%'
9 )
10 where rn between 41 and 45
11 /
OWNER NAME TYPE
LINE
TEXT
RN CNT
SYS ANYDATA TYPE
13
STATIC FUNCTION ConvertVarchar(c IN VARCHAR) return AnyData,
41 999744
SYS ANYDATA TYPE
11
STATIC FUNCTION ConvertDate(dat IN DATE) return AnyData,
42 999744
SYS ANYDATA TYPE
9
43 999744
SYS ANYDATA TYPE
7
They serve as explicit CAST functions from any type in the Oracle ORDBMS
44 999744
SYS ANYDATA TYPE
6
enable construction of the AnyData in its entirity with a single call.
45 999744
Elapsed: 00:00:41.02
SQL> ed
Wrote file afiedt.buf
1 select n.name, m.value from v$statname n, v$mystat m
2 where n.statistic# = m.statistic#
3* and (upper(name) like '%SORT%' or upper(name) like '%TEMP%')
SQL> /
NAME VALUE
physical reads direct temporary tablespace 35446
physical writes direct temporary tablespace 17723
RowCR attempts 0
SMON posted for dropping temp segment 0
sorts (memory) 36
sorts (disk) 1
sorts (rows) 1999596
OTC commit optimization attempts 0
8 rows selected.here is the second one returning only rows:
SQL> ed
Wrote file afiedt.buf
1 select *
2 from (
3 select i.*,
4 row_number() over(order by owner, name, type) rn
5 --, -- used for pagination
6 -- count(*) over(partition by 1) cnt -- total count of rows found for this search
7 from big i
8 where owner like 'S%' and name like '%A%'
9 )
10* where rn between 41 and 45
SQL> /
OWNER NAME TYPE
LINE
TEXT
RN
SYS ANYDATA TYPE
13
STATIC FUNCTION ConvertVarchar(c IN VARCHAR) return AnyData,
41
SYS ANYDATA TYPE
11
STATIC FUNCTION ConvertDate(dat IN DATE) return AnyData,
42
SYS ANYDATA TYPE
9
43
SYS ANYDATA TYPE
7
They serve as explicit CAST functions from any type in the Oracle ORDBMS
44
SYS ANYDATA TYPE
6
enable construction of the AnyData in its entirity with a single call.
45
Elapsed: 00:00:12.09
SQL> select n.name, m.value from v$statname n, v$mystat m
2 where n.statistic# = m.statistic#
3 and (upper(name) like '%SORT%' or upper(name) like '%TEMP%')
4 /
NAME VALUE
physical reads direct temporary tablespace 0
physical writes direct temporary tablespace 0
RowCR attempts 0
SMON posted for dropping temp segment 0
sorts (memory) 10
sorts (disk) 0
sorts (rows) 999812
OTC commit optimization attempts 0
8 rows selected.So execution time 41 sec vs 12 sec
sorts (rows) 1 999 596 vs 999 812
physical reads/writes direct temporary tablespace 35446/17723 vs 0/0
I assume that for a small overall returned row count it probably is OK, but for less restrictive search it can be quite deadly as before with two queries.
Gints Plivna
http://www.gplivna.eu -
Getting A Count In One SQL Statement
Since I don't know how to do what I'm about to ask, I would normally create a table (tbl1) with the main dataset I want and then create a second table (tbl2) with additional data I want, join the two and update tbl1 data with tbl2 data.
However, I would like to know how to do this in one SQL statement. I somehow need to link the count sql with the main body..?
So..I have to pull data by group id. Each group id can have a certain number of active members in it. I would like to use one SQL statement to pull the group id's and also, at the same time, give me a count of each group's active membership. Both the main and count statments in the below SQL include the emp_grps table which can obviously be linked so the right groups are updated..
Not sure how to begin to reflect this in an SQL statement, so I'll just give you the wrong version to show what data elements I have. The following gives the total count by all group's in each groups individual record. Of course, as mentioned, all I want is that group's share of the membership in their individual record:
select group_id,
(select count(*)
from elig elg
join emp_grps eg
on elg.group_id = eg.group_id
where eg.rmc_code in ('CR')
and elg.elig_start_date < sysdate
and elg.elig_end_date > sysdate) mbr_count
from odw.emp_grps eg
where eg.rmc_code in ('1M')
Output from this query:
GROUP_ID MBR_COUNT
A 10,000
B 10,000
C 10,000
D 10,000
What I want to see:
GROUP_ID MBR_COUNT
A 7,000
B 1,000
C 1,500
D 500
Thanks for any assistance..Hi,
So you want one row for every distinct value of group_id, with a count that reflects just that group_id.
That sound like a job for GROUP BY group_id and the aggregate COUNT function, like this:
SELECT eg.group_id
, COUNT ( CASE
WHEN eg.rmc_code IN ('CR')
THEN 1
END
) AS mbr_count
FROM elig elg
JOIN emp_grps eg ON elg.group_id = eg.group_id
WHERE eg.rmc_code IN ('CR', '1M')
AND elg.elig_start_date < SYSDATE
AND elg.elig_end_date > SYSDATE
GROUP BY eg.group_id
HAVING COUNT ( CASE
WHEN eg.rmc_code IN ('1M')
THEN 1
END
) > 1
ORDER BY eg.group_id
;It's unclear what you're trying to do with eg.rmc_code. I'm guessing you want to count the rows where it's one value ('CR'), but only display groups that also have another value ('1M').
Of course, I can't say for sure without seeing your actual tables, or at least small test versions of them.
Post CREATE TABLE and INSERT statements (relevant columns only) for all tables involved, and the resutls you want from that sample data (if it's not the results you already posted).
Always say which version of Oracle you're using. -
Can I write merge SQL statement having count(*)?
Hi this is a followup question of my previous post. I tried to use a merge SQL statement to solve my problem but now I bump into another problem.
Now I have a table where the field I need to update is a partial PK
when using a merge SQL statement, I have to put a where clause that check if count(*) = 1 because of the PK constraint
Where can I put the count(*) = 1 clause?
Here are the details:
I have two tables TA and TB, where TA contains the fields ID, FULLNAME, TYPE and TB contains the fields ID, FIRSTNAME
I want to update the firstnames in TB to be the firstnames from TA where TB.ID = TA.ID and TA.TYPE = 'ABC'
{ID, FIRSTNAME} are PKs but for the same ID, there can be more than 1 firstname.
e.g.
TA
ID | FULLNAME | TYPE
1 Caroline T ABC
2 Mary C DEF
3 Peter J ABC
TB
ID | FIRSTNAME
1 Caroline
1 Carol
1 C,
3 Peter
I need to update TB with the new firstnames from TA where type is 'ABC' but only for those fields that have count(TB.ID) = 1
when I try to run this SQL statement
merge into TB B using TA A
on (A.ID = B.ID and A.TYPE = 'ABC')
when matched then update set B.FIRSTNAME = substr(A.FULLNAME, 1, instr(A.FULLNAME, ',') - 1)
I got this error SQL Error: ORA-00001: unique constraint (TEST.PK_TB) violated
which I believe is because I updated those fields say ID = 1, all with 'Caroline'
that means I will have to add a clause having count(TB.ID) = 1
How would you do it?
Server is Oracle 11g
Thank you!Hi,
One way is to join ta and tb in the USING clause, and eliminate the duplicates there.
MERGE INTO tb dst
USING (
SELECT ta.id
, REGEXP_SUBSTR ( MIN (ta.fullname)
, '^[^,]*'
) AS firstname
FROM ta
JOIN tb ON ta.id = tb.id
WHERE ta.type = 'ABC'
GROUP BY ta.id
HAVING COUNT (*) = 1
) src
ON (scr.id = dst.id)
WHEN MATCHED THEN UPDATE
SET dst.firstname = src.firstname
;If you'd care to post CREATE TABLE and INSERT statements for your sample data, then I could test this.
I used REGEXP_SUBST instead of SUBSTR and INSTR to find the firstname, because I find it a little cleaner, and becuase it returns something even when there is no ',' in fullname, which I'm guessing is what you really want. (None of the fullnames in your sample data have ','s.) You could use SUBSTR and INSTR instead. -
The column name "PERNR" has two meanings. ABAP/4 Open SQL statement.
Hi All,
Could anyone advise on what are the error I encountered at below code.
I get the error in " The column name "PERNR" has two meanings. ABAP/4 Open SQL statement." . This errors happen to all the key fields I have selected in below code (eg: pernr, subty, objps, sprps, begda, endda, seqnr).
The field zeih also encountered error in "Unknown column name "ZEIH". not determined until runtime, you cannot specify a field list."
SELECT pernr
subty
objps
sprps
begda
endda
seqnr
zlsch
ZEIH
SELECT * INTO CORRESPONDING FIELDS
OF TABLE i_pa0009
FROM pa0001 INNER JOIN pa0009
ON pa0001pernr = pa0009pernr
WHERE bukrs IN s_code AND
banks NE space.Hi,
In this query
SELECT pernr
subty
objps
sprps
begda
endda
seqnr
zlsch
ZEIH
if you have used joins and if both the database pa0001, pa0009 has the above mentioned fields you will get the error message as the control gets confused as to which table of the field you are referring to..., instead use them in this way
SELECT pa0001~pernr
for each field mention to which table it belongs and ~ before the field name in the above fashion, this will remove the error
Regards,
Siddarth -
How to tune the following sql statements which has two unions in oracle 10g
It takes a long time to run the following sql statement in 10g. Each select brings back about 4 million rows and there will be about 12 million rows. When I run each select statements seprately in sqlplus I can see the data immedaitely but when I run it as whole with two unions in the select it just takes very very long time? I want to know how to make this run faster? Can we add hints? or is it because of any table space? Any help is appreciated.
select
D.EMPLID
,D.COMPANY
,'CY'
,D.CALENDAR_YEAR
,D.QTRCD
,D.ERNCD
,D.MONTHCD
,D.MONTHCD
,D.GRS_MTD
,D.GRS_QTD
,D.GRS_YTD
,D.HRS_MTD
,D.HRS_QTD
,D.HRS_YTD
from PS_EARNINGS_BAL D
where D.SPCL_BALANCE = 'N'
union
select
D.EMPLID
,D.COMPANY
,'FY'
,(case when D.MONTHCD > '06' then D.CALENDAR_YEAR + 1 else D.CALENDAR_YEAR end)
,ltrim(to_char(to_number(D.QTRCD) + decode(sign(3-to_number(D.QTRCD)),1,2,-2),'9'))
,D.ERNCD
,ltrim(to_char(to_number(D.MONTHCD) + decode(sign(7-to_number(D.MONTHCD)),1,6,-6),'09'))
,D.MONTHCD
,D.GRS_MTD
,D.GRS_QTD
,(select sum(F.GRS_MTD) from PS_EARNINGS_BAL F where
F.EMPLID = D.EMPLID and
F.COMPANY = D.COMPANY and
F.ERNCD = D.ERNCD and
F.SPCL_BALANCE = D.SPCL_BALANCE and
(case when F.MONTHCD < '07' then F.CALENDAR_YEAR -1 else F.CALENDAR_YEAR end)
= (case when D.MONTHCD < '07' then D.CALENDAR_YEAR -1 else D.CALENDAR_YEAR end)
and to_number(F.MONTHCD) + decode(sign(7-to_number(F.MONTHCD)),1,6,-6)
<= to_number(D.MONTHCD) + decode(sign(7-to_number(D.MONTHCD)),1,6,-6))
,D.HRS_MTD
,D.HRS_QTD
,(select sum(F.HRS_MTD) from PS_EARNINGS_BAL F where
F.EMPLID = D.EMPLID and
F.COMPANY = D.COMPANY and
F.ERNCD = D.ERNCD and
F.SPCL_BALANCE = D.SPCL_BALANCE and
(case when F.MONTHCD < '07' then F.CALENDAR_YEAR -1 else F.CALENDAR_YEAR end)
= (case when D.MONTHCD < '07' then D.CALENDAR_YEAR -1 else D.CALENDAR_YEAR end)
and to_number(F.MONTHCD) + decode(sign(7-to_number(F.MONTHCD)),1,6,-6)
<= to_number(D.MONTHCD) + decode(sign(7-to_number(D.MONTHCD)),1,6,-6))
from PS_EARNINGS_BAL D
where D.SPCL_BALANCE = 'N'
union
select
D.EMPLID
,D.COMPANY
,'FF'
,(case when D.MONTHCD > '09' then D.CALENDAR_YEAR + 1 else D.CALENDAR_YEAR end)
,ltrim(to_char(to_number(D.QTRCD)+decode(sign(4-to_number(D.QTRCD)),1,1,-3),'9'))
,D.ERNCD
,ltrim(to_char(to_number(D.MONTHCD)+decode(sign(10-to_number(D.MONTHCD)),1,3,-9),'09'))
,D.MONTHCD
,D.GRS_MTD
,D.GRS_QTD
,(select sum(F.GRS_MTD) from PS_EARNINGS_BAL F where
F.EMPLID = D.EMPLID and
F.COMPANY = D.COMPANY and
F.ERNCD = D.ERNCD and
F.SPCL_BALANCE = D.SPCL_BALANCE and
(case when F.MONTHCD < '10' then F.CALENDAR_YEAR -1 else F.CALENDAR_YEAR end)
= (case when D.MONTHCD < '10' then D.CALENDAR_YEAR -1 else D.CALENDAR_YEAR end)
and to_number(F.MONTHCD)+decode(sign(4-to_number(F.MONTHCD)),1,9,-3)
<= to_number(D.MONTHCD)+decode(sign(4-to_number(D.MONTHCD)),1,9,-3))
,D.HRS_MTD
,D.HRS_QTD
,(select sum(F.HRS_MTD) from PS_EARNINGS_BAL F where
F.EMPLID = D.EMPLID and
F.COMPANY = D.COMPANY and
F.ERNCD = D.ERNCD and
F.SPCL_BALANCE = D.SPCL_BALANCE and
(case when F.MONTHCD < '10' then F.CALENDAR_YEAR -1 else F.CALENDAR_YEAR end)
= (case when D.MONTHCD < '10' then D.CALENDAR_YEAR -1 else D.CALENDAR_YEAR end)
and to_number(F.MONTHCD)+decode(sign(4-to_number(F.MONTHCD)),1,9,-3)
<= to_number(D.MONTHCD)+decode(sign(4-to_number(D.MONTHCD)),1,9,-3))
from PS_EARNINGS_BAL D
where D.SPCL_BALANCE = 'N'
Edited by: user5846372 on Mar 11, 2009 8:55 AMHi,
What i observed is that your table name and where clause is same in all the thress SELECTs whereas columns having some manipulations that is not going to be unique. I guess you can easily replace UNION with UNION ALL.
from PS_EARNINGS_BAL D
where D.SPCL_BALANCE = 'N'Note: I am not aware of your data and business requirement. Please test the result before removing. It is just a suggetion
Cheers,
Avinash -
SQL Statement / Count & Percentage
Hello All,
Below is the SQL statement that I'm using with an MS Access database. Now, I'm looking for an SQL statement that will get the same results using an SQL Compact database.
Here is what I am using with MS Access that works great:
queryString = "SELECT DStatus, Count(DStatus) As CountOfSummaryItem, (Count(*)/(Select count(*) FROM tbl_Records_DR)) as Percentage From tbl_Records_DR GROUP BY DStatus Order BY Count(DStatus) DESC;"
Results are something like this out of a total 50 records in the database:
Status - Count - Percentage
Broken - 5 - 10%
Stopped - 10 - 20%
Return - 20 - 40%
Closed - 15 - 30%
Thanks,
ADawn
ADawnSQL Server Compact has limited support for subqueries. I would suggest:
SELECT DStatus, Count(*) FROM tbl_Records_DR GROUP BY DStatus
to get the record count per "DStatus", and load the results on a generic List<> object, where you would do the math in code, or else, get first the total record count into a int variable, executing a scalar command with the following instruction
(C#):
SqlCeCommand totalCountCommand = new SqlCeCommand("SELECT Count(*) FROM tbl_Records_DR", myConnection);int i = (int)totalCountCommand.ExecuteScalar();
...and then use that value on the following instruction, either using string concatenation or a command parameter to divide each value fot the total count...
SqlCeCommand rowCountCommand = new SqlCeCommand("SELECT DStatus, Count(*), Count(*)/" + i.ToString() + " * 100 AS Percentage FROM tbl_Records_DR GROUP BY DStatus", myConnection);SqlCeDataReader r = rowCountCommand.ExecuteReader();
This is not tested code, it's just meant to give you an idea on how to get the result.
Alberto Silva Microsoft MVP - Device Application Development - http://msmvps.com/AlbertoSilva moving2u - R&D Manager - http://www.moving2u.pt -
The best way to do paging and get total rows count given a sql statement
Hi,
Just got a quick question.... what is the best way to do paging as well as the total rows count given by a sql statement.
e.g. "select * from emp"
1. I need to know the total row count for this statement.
2. I also need to do a 10 rows per page....
Is there a way to do it in a SINGLE statement for best performance?
Thanks experts.Sounds more like a "formatting" problem...
If Sql*plus is your reporting tool, check out the guide:
http://download-west.oracle.com/docs/cd/B10501_01/server.920/a90842/toc.htm -
Can you really update two tables in one SQL statement
Ok a post in the forum has got me awefully curious:
Can you update two tables in one update statement i.e something like this
update table a , b
set b.<column> = something
a.<column> = something
Something to this effect.
If you are curious to know what post I am talking about it is called "updating a single row"No. You can only update one table in one SQL statement.
-
Getting difference from values of two different SQL Statements
Hello,
I have two SQL Queries like the following:
1. Statement:
SELECT name, SUM(a1), SUM(b1),SUM(c1),SUM(d1)
FROM table 1, table 2
WHERE ...
GROUP BY name
2. Statement:
SELECT name, SUM(a2), SUM(b2),SUM(c2),SUM(d2)
FROM table 3, table 4
WHERE ...
GROUP BY name
I need now a combination of these SQL Statements in one Statement where the result should be the following records
name, a1-a2 as a, b1-b2 as b, c1-c2 as c, d1-d2 as d
Name is a VARCHAR and in both queries the values of the field name are the same
all other fields are integer.
I hope someone can help me.
RegardsYou can use this
with t1 as (
SELECT name, SUM(a1) as a1, SUM(b1) as b1,SUM(c1) as c1,SUM(d1) as d1
FROM table 1, table 2
WHERE ...
GROUP BY name
), t2 as (
SELECT name, SUM(a2) as a2, SUM(b2) as b2,SUM(c2) as c2,SUM(d2) as d2
FROM table 3, table 4
WHERE ...
GROUP BY name
), tt as (
select name
from t1
union
select name
from t2
select *
from tt
natural left outer join t1
natural left outer join t2
where a1 <> a2
or b1 <> b2
or c1 <> c2
or d1 <> d2Bye Alessandro
Maybe you are looking for
-
Avoiding Firmware Upgrade Grief
Assuming that you have a non-UDP (User Data Preservation) phone, like the N95, a firmware upgrade can be a major thrash. Many posts in this forum attest to these problems, but they continue to occur, in part because of inadequate instructions. Here a
-
Transaction to see result of inbound idoc ( XI to SAP R3) ?
Hi, may i know the transaction to see whether the inbound idoc has created the record ? i'm sending idoc from XI to ECC. Farah
-
Dynamic select with field symbols
Hi guys, I have 2 tables. First table is the popup fields using fm popup_get_values: tab1-tabname tab1-fieldname tab1-value Second table is the input fields to be displayed in the popup box: tab2-transactno tab2-docno tab2-customer tab2-postdate etc.
-
I have CS4 but am installing CS6 rather than upgrading. Do I need to uninstall CS4?
I am still using CS4 at prepsent but am installing the complete CS6 rather than upgrading. Do I need to uninstall CS4 or is that taken care of when installing CS6?
-
FireWire fried by power cut?
Someone switched off the power to my iMac the other day. Since I've rebooted: a) System Profiler shows no awareness of FireWire ("Unable to list FireWire devices" in red) b) Every boot takes about five minutes, 3+ of which seems to be spent waiting f