Getting DISTINCT count from two different columns
Hi all,
I have following query which gives currency code from two different tables. I would like to get the distinct count of currency codes from these two different columns.
SELECT eb.person_seq_id, eb.bonus_amount, eb.currency_cd, ed.currency_cd_host
FROM fr_emp_bonuses eb, fr_emp_details ed, fr_periods p
WHERE eb.person_seq_id = ed.person_seq_id AND ed.period_seq_id = eb.period_seq_id
AND ed.period_seq_id = p.period_seq_id AND p.period_status = 'CURRENT'
AND eb.bonus_amount >= 0 AND eb.person_seq_id = 3525125;
This query gives following result
3525125 240000 USD INR
3525125 0 USD INR
3525125 60000 USD INR
3525125 50000 USD INR
There are two distinct currency codes (USD, INR) and total amount is 350000. So I am looking for a query to give me the following result
3525125 350000 2
Thanks in advance
Hi,
Here's one way:
WITH original_query AS
SELECT eb.person_seq_id
, eb.bonus_amount
, eb.currency_cd
, ed.currency_cd_host
FROM fr_emp_bonuses eb
, fr_emp_details ed
, fr_periods p
WHERE eb.person_seq_id = ed.person_seq_id
AND ed.period_seq_id = eb.period_seq_id
AND ed.period_seq_id = p.period_seq_id
AND p.period_status = 'CURRENT'
AND eb.bonus_amount >= 0
AND eb.person_seq_id = 3525125
, unpivoted_data AS
SELECT person_seq_id
, bonus_amount
, currency_cd
FROM original_query
UNION ALL
SELECT person_seq_id
, 0 AS bonus_amount
, currency_cd_host AS currency_cd
FROM original_query
SELECT person_seq_id
, SUM (bonus_amount) AS total_bonus_amount
, COUNT (DISTINCT currency_cd) AS distinct_currency_cds
FROM unpivoted_data
GROUP BY person_seq_id
;There may be a shorter, more efficient way to get the same results, but without knowing more about your tables, I can't tell.
The tricky thing is getting two columns (currency_cd and currencuy_cd_host in this case) counted together. You can't simply say
COUNT (DISTINCT eb.currency_cd) +
COUNT (DISTINCT ed.currency_code_host)That happens to get the correct result with the sample data you posted, but what if you had data like thEe following?
currency_cd currency_cd_host
INR USD
USD INRHere, the count of distinct currency_cds is 2, and the count of distinct currency_cd_hsots is also 2. Does that mean the grand total is 2 + 2 = 4? No, the 2 codes in one column arte the same 2 codes as in the other column. We need to get both currency_cd and currency_cd_hsot into the same column, and then do COUNT (DISTINCT ...) on that combined column. A UNION, as shown above, will certainly do that, starting with your query as you posted it. The query you posted isn't necessarily the best frist step towards this result, however, so there may be a much better approach, depending on your tables.
Edited by: Frank Kulash on Feb 1, 2012 6:21 PM
Here's a slightly shorter, and probably more efficient way to get the same results:
WITH cntr AS
SELECT LEVEL AS n
FROM dual
CONNECT BY LEVEL <= 2
SELECT eb.person_seq_id
, SUM (eb.bonus_amount) AS total-amount
, COUNT ( DISTINCT CASE
WHEN c.n = 1
THEN eb.currency_cd
ELSE ed.currency_cd_host
END
) AS distinct_currency_cds
FROM fr_emp_bonuses eb
, fr_emp_details ed
, fr_periods p
, cntr c
WHERE eb.person_seq_id = ed.person_seq_id
AND ed.period_seq_id = eb.period_seq_id
AND ed.period_seq_id = p.period_seq_id
AND p.period_status = 'CURRENT'
AND eb.bonus_amount >= 0
AND eb.person_seq_i = 3525125
-- NOTE: no join condition involving c; we really do want a cross-join
GROUP BY eb.person_seq_id
;
Similar Messages
-
How to get a rowcount from two different schema in two different databases?
Hello,
I want to count of rows in each table in a schema say test, of DEV1 database to another schema say test of DEV2 database. both have same schema data in both the databases. my output should look something like this.
Tablename
database name DEV!, schema name test , tablename: count
database name DEV2, schema name test , tablename: count
can someone help me please.
Thanks a lotGive this a try in dba1 - assuming there is a db link in dba1 to dba2:
select 'DBA1', count(*) from table
union all
select 'DBA2', count(*) from table@dba2
Note that if these are large tables, you may want to gather stats on the two tables (IMPORTANT) and then do
select 'DBA1', num_rows from all_tables where table_name = 'TABLE'
union all
select 'DBA2', num_rows from all_tables@dba2 where table_name = 'TABLE'
If you don't gather stats - the num_rows column in all_tables will reflect the number of rows that were present when stats were last gathered and will not reflect any inserts/deletes that have taken place since.
The "union all" clause differs from "union" in that "union all" shows every matching result from both halves of the union - whereas union will only show each unique result once.
Hope this helps! -
Can't get table field from two different tables if named same
select c.notes, o.notes
from cusomters c, orders o
:does not work in getting the RS.
:if i change database to:
select c.customer_notes, o.order_notes
from cusomters c, orders o
:then it works.
:i make PURE DYNAMIC META SQL database
applicaitons, and i need for abstract SQL tables.
i have the same problem in getting
the max values:
select
max(height),
max(weight),
max(age)
from person_stats
group by geographical_areaWhen you select from 2 different tables you need to join them on some condition, otherwise it has no idea how to associate the 2 tables together.
try select c.notes, o.notes from cusomters c, orders o where c.customer_id = o.customer.id or whatever the join fields are.
For the group by I believe you have to include the field that you group by:
select geopraphical_area, max(height), max(weight), max(age) from person_stats group by geographical_area
give them a try
Jamie -
Get user count from two tables and display in 1 row
I have 2 tables.....
Table1 Table2
user date user date
With 1 query, I want to display the user, the count of the number of times a user appears in Table1.user as count1 and the count of the number of times that same user appears in Table2.user as count2 between a specific time period. I have looked and tried things including joins, unions, nested loops but can't get anything to work. The result would appear like this:
USER COUNT1 COUNT2
john 100 2
doe 1000 200
Thank you for your time. I'm really stuck and confused.Hi,
Welcome to the forum!
I think the easiest way to do this is to do a GROUP BY query on each table separately, and then combine the results, using FULL OUTER JOIN or UNION.
WITH union_data AS
SELECT user_name
, COUNT (*) AS count1
, 0 AS count2
FROM table1
WHERE dt >= &start_dt
AND dt < &end_dt + 1
GROUP BY user_name -- Forgot this originally!
UNION ALL
SELECT user_name
, 0 AS count1
, COUNT (*) AS count2
FROM table2
WHERE dt >= &start_dt
AND dt < &end_dt + 1
GROUP BY user_name -- Forgot this originally!
SELECT user_name
, SUM (count1) AS count1
, SUM (count2) AS count2
FROM union_data
GROUP BY user_name
;Edited by: Frank Kulash on Jul 29, 2009 1:34 PM
Edited by: Frank Kulash on Jul 29, 2009 2:46 PM
As Solomon pointed out, I forgot the GROUP BY clauses in the sub-query.
Without the tables, I can't test it. -
To calculate variance from two different columns
Hi
I have a table like this
create table temp1
(f_name varchar2(100),
f_month_Year Varchar2(10),
f_amount integer
Records in this table will be like this:
f_name f_month_Year f_amount
Ajay 092007 500
Bhavani 092007 700
Bhavani 102007 200
Ajay 102007 100
I would like to get the Output like following:
092007(Previous Month) 102007(Current Month) Variance
Ajay 500 100 400
Bhavani 700 200 500
the variance should be precalculated in the query itself.
Please help me on this.
Regards
SankarLAG
<br>
<br>
Example:
<br>
<br>
SQL> select * from t;
NAME DT AMT
Ajay 092007 500
Bhavani 092007 700
Bhavani 102007 200
Ajay 102007 100
SQL> select name,curr,pre,pre-curr var
2 from
3 (select name,
4 lag(amt) over(partition by name order by to_date(dt,'mmyyyy')) pre,
5 amt curr,dt
6 from t
7 )
8 where dt = to_char(sysdate,'fmmmyyyy');
NAME CURR PRE VAR
Ajay 100 500 400
Bhavani 200 700 500 -
How to get Distinct Count of Products across two dimensions
Hi,
I have two dimensions, Item and Presentations. I need to get distinct count of products for IMD_Id + Merc_Pres_Id. IMD_Id is the lowest member in Item and Merc_Pres_Id is lowest in Presentation. My MDX query is given below but when I apply filters to
slice it, it does not work and does not give right count. It always gives the count for all.
/* Last Year Demand - Demand for 12 months back of selected months */
With
Member [Measures].[LYDemand]
as
Sum(
Generate(
EXISTING[All Date].[Fiscal Month Name].[Fiscal Month Name].Members,
{parallelperiod([All Date].[Fiscal Month Name].[Fiscal Month Name], 12
,[All Date].[Fiscal Month Name].CurrentMember)}
,[Measures].[Proj Demand]
/* Last to last Year Demand - Demand for 24 back of selected months */
Member [Measures].[LLYDemand]
as
Sum(
Generate(
EXISTING[All Date].[Fiscal Month Name].[Fiscal Month Name].Members,
{parallelperiod([All Date].[Fiscal Month Name].[Fiscal Month Name], 24
,[All Date].[Fiscal Month Name].CurrentMember)}
,[Measures].[Proj Demand]
/* Current Year Active Products */
Member [Measures].[CYCount]
as
CASE
WHEN
[Measures].[Proj Demand] > 0
THEN
DistinctCount(Existing(([All Items].[IMD Id].[IMD Id],[All Merchandise Presentations].[Merch
Pres Key].[Merch Pres Key])))
ELSE
NULL
END
/* Last year Active Products */
Member [Measures].[LYCount]
as
CASE
WHEN
[Measures].[LYDemand] > 0
THEN
DistinctCount(([All Items].[IMD Id].[IMD Id],[All Merchandise Presentations].[Merch Pres Key].[Merch Pres
Key], [All Items].[Style Name].CurrentMember, (StrToMember('[All Date].[Fiscal Month Name].&[201401]',CONSTRAINED).Lag(12)
: StrToMember('[All Date].[Fiscal Month Name].&[201411]',CONSTRAINED).Lag(12))))
ELSE
NULL
END
/* Last to last Year Active Products */
Member [Measures].[LLYCount]
as
CASE
WHEN
[Measures].[LLYDemand] > 0
THEN
DistinctCount(([All Items].[IMD Id].[IMD Id],[All Merchandise Presentations].[Merch Pres Key].[Merch Pres
Key], [All Items].[Style Name].CurrentMember, (StrToMember('[All Date].[Fiscal Month Name].&[201401]',CONSTRAINED).Lag(24)
: StrToMember('[All Date].[Fiscal Month Name].&[201411]',CONSTRAINED).Lag(24))))
ELSE NULL END
SELECT
[Measures].[CYCount], [Measures].[LYCount], [Measures].[LLYCount],
[Measures].[Proj Demand],[Measures].[LYDemand],[Measures].[LLYDemand]
ON
COLUMNS,
Non
Empty([All Items].[Demand Center Name].[Demand Center Name], [All Items].[Style Name].[Style Name])
ON ROWS
FROM
(SELECT (StrToSet('[All Items].[Style].[ALL]'))
ON COLUMNS
FROM
(SELECT (StrToSet('[All Items].[Demand Center].[ALL]'))
ON COLUMNS
FROM
(select (STRTOSET('[All Items].[Merch Group].&[MG-110]'))
on Columns
FROM
(SELECT (StrToSet('[All Merchandise Presentations].[Merch Pres Chnl Dkey].&[MPC-1]'))
ON COLUMNS
From
[FMI Forecasting]
WHERE {strToMember('[All Date].[Fiscal Month
Name].&[201401]',CONSTRAINED) :
StrToMember('[All Date].[Fiscal Month Name].&[201411]',CONSTRAINED)}
Requirements are as follows:
1. Distinct Count should not include products where Proj Demand is 0, when I am using Filter function to remove products with 0 demand, query is really slow and execution time goes up from 35- 40 secs to 8-9 Minutes.
2. When we apply filter (parameters) Distinct Count should be in the context of filters( which are mentioned in the select statement like Style, Demand Center and Merch Group). Currently after applying filters count does not change.
Thanks for help.Hi Skd78,
Thank you for your question.
I am trying to involve someone more familiar with this topic for a further look at this issue. Sometime delay might be expected from the job transferring. Your patience is greatly appreciated.
Thank you for your understanding and support.
Regards,
Charlie Liao
TechNet Community Support -
How can I get these two results in two different columns?
SELECT COUNT(attr_id)
FROM pv_attribute
WHERE port_id = 322;
SELECT COUNT(attr_id)
FROM pv_attribute
WHERE port_id = 323;
How can I get these two results in two different columns?
ThanksSo Jens made a tiny mistake with the column name... shame you couldn't be bothered to research Pivoting so you could have corrected the mistake (possibly it was deliberate *{:-) ) and learnt something.
with pv_attribute as (select 16123 attr_id, 322 port_id from dual union all
select 16123 attr_id, 322 port_id from dual union all
select 19223 attr_id, 322 port_id from dual union all
select 11193 attr_id, 323 port_id from dual union all
select 13163 attr_id, 323 port_id from dual)
-- end of test data setup
select sum(decode(port_id, 322, 1, 0)) cnt_322,
sum(decode(port_id, 323, 1, 0)) cnt_323
from pv_attribute
where port_id in (322, 323) -
Filename seperately & Putting data from Hash Map to two different columns
The following code produces the output as :
$ java getNamefile
File Name : reaper.txt
File Name : Testing
Is it possible to just get the file name "reaper" from it instead of reaper.txt
import java.io.*;
class getNamefile
public static void main(String[] args)
File f1 = new File("C:/javamyprograms/reaper.txt");
File f2 = new File("C:/javamyprograms/Testing/");
System.out.println("File Name : " + f1.getName());
System.out.println("File Name : " + f2.getName());
}Secondly I am trying to put the values from a HashMap into ".xls"
PrintWriter out = new PrintWriter (new FileWriter("Unique_words_count" + file) + ".xls");
and out.write(key + " " + hm.get(key));
This put the values in the same columns. I want the results to be two different columns like
column1 column2
key1 value1
key2 value2
Please do advise. Thanks in advance.Is it possible to just get the file name "reaper"from it instead of reaper.txtActually, I ran a test, and
System.out.println( "file name portion == " + ( f.getName().split( "\\." ) )[ 0 ] );works also:
This has the same effect as:
String fileName = f.getName();
String splitFileName[] = fileName.split( "\\." );
System.out.println( "file name portion == " + splitFileName[ 0 ] );Now that I think about it, the second form is more easily understood. There is really no reason to do it the first way. Just interesting to note that you can. -
Concatenate columns from two different reports
In OBIEE 11g report, I am looking for a method to concatenate columns from two different reports.
My requirement is, if I show 'Units Produced' for customer A, I need to show another column 'Units Produced' for a related customer B.
Every customer has one related customer.
So my report shows all the data for customer A, but I need to add one column which is for custome B , so I am looking a way to concatenate columns or if some other way this can be doneCustomer A is dimension table. You mapped to fact to get Customer A details.
Now you want for Customer B. Now create one more alias table for Customer and name it as customer B and join with Fact on Customer B keys and use it.
Each customer has related customer.
2 dimension tables one for customer and other for related customer. -
How to Create a new column from two different result sets
How to Create a new column from two different result sets, both the result set uses the different date dimensions.
i got solutions for this is apply filters in column formula it self, based on the requirement.
-
Revision: 21394
Revision: 21394
Author: [email protected]
Date: 2011-06-16 12:34:13 -0700 (Thu, 16 Jun 2011)
Log Message:
bug fix for watson 2887837 Not getting duplicate session detected error when same flex client id is used from two different HTTP sessions in CRX.
get the sessions id before we invalidate the duplicate session.
Checkintests pass
Modified Paths:
blazeds/trunk/modules/core/src/flex/messaging/endpoints/BaseHTTPEndpoint.javaFor our profect I think this issue was caused as follows:
Believing that remoting was full asynchronous we fired a 2 or 3 remote calls to the server at the same time ( within the same function ) - usually when the users goes to a new section of the app.
This seemed to trigger the duplicate http session error since according to http://blogs.adobe.com/lin/2011/05/duplication-session-error.html two remote calls arriving before a session is created will cause 2 sessions to be created.
Our current solution ( too early to say it works ) is to daisy chain the multiple calls together .
Also there seemed to be an issue where mobile apps that never quit ( thanks Apple! ) caused the error when activated after a few hours.
I guess the session expires on the server and the error above occurs on activation.
So the mobile apps now ping the server with a remote call when activated after sleeping for more than one hour.
All duplicate http errors are silently caught and reported.
Fingers crossed we won't get any more! -
Sum two different columns from two different tables
Can you select and sum two different columns, from two different tables in the same sql statement?
i.e.
table1
Item----OnHand_Qty
A--------10
A--------15
B--------10
B--------10
C--------20
table2
Item----Trx_Qty
A--------2
A--------4
A--------6
B--------1
B--------1
C--------4
I'm looking for the following results from a query
Item----Sum(Onhand_Qty)---Sum(Trx_Qty)
A--------25Like this?
SQL> create table table1 (item,onhand_qty)
2 as
3 select 'A', 10 from dual union all
4 select 'A', 15 from dual union all
5 select 'B', 10 from dual union all
6 select 'B', 10 from dual union all
7 select 'C', 20 from dual union all
8 select 'D', 30 from dual
9 /
Tabel is aangemaakt.
SQL> create table table2 (item, trx_qty)
2 as
3 select 'A', 2 from dual union all
4 select 'A', 4 from dual union all
5 select 'A', 6 from dual union all
6 select 'B', 1 from dual union all
7 select 'B', 1 from dual union all
8 select 'C', 4 from dual union all
9 select 'E', 3 from dual
10 /
Tabel is aangemaakt.
SQL> select nvl(t1.item,t2.item) item
2 , t1.sum_onhand_qty
3 , t2.sum_trx_qty
4 from ( select item, sum(onhand_qty) sum_onhand_qty
5 from table1
6 group by item
7 ) t1
8 full outer join
9 ( select item, sum(trx_qty) sum_trx_qty
10 from table2
11 group by item
12 ) t2
13 on (t1.item = t2.item)
14 /
I SUM_ONHAND_QTY SUM_TRX_QTY
A 25 12
B 20 2
C 20 4
E 3
D 30
5 rijen zijn geselecteerd.Regards,
Rob. -
I have copied my music library from two different files from extewrnal hard drive into the Itunes folder. I tunes only recognizes some of the songs. I have reloaded 5 times and can't get intunes to recognize all my songs? HELP!
" When I did this, my library showed all the music I have "purchased" from itunes but did not have the music that I downloaded a long time ago through itunes from my old CDs."
Correct.
" How can I get that music to show up in my library now on my new computer? "
Copy it from your old computer or your backup copy of your old computer.
The sync is one way - computer to ipod. -
Extracting unique records from two different tables record
Hello,
In the following code of two different tables www.testing.com exists in both tables. I want to compare two different columns of the two different tables to get unique records.
SQL> select unique(videoLinks) from saVideos where sa_id=21;
VIDEOLINKS
www.testing.com
SQL> ed
Wrote file afiedt.buf
1* select unique(picLinks) from saImages where sa_id=21
SQL> /
PICLINKS
test
test14
www.hello.com
www.testing.comThanks & best regardsUnfortunatly you didn't mention the expected output. I guess it would be the one line
"www.testing.com"
in that case simply join the two tables.
select *
from saVideos v
join saImages i on i.sa_id = v.sa_id and i.picLinks = v.videoLinks
where v.sa_id=21;If needed then you could change the select list to retrieve only distinct values.
select unique v.sa_id, v.videolinks
from saVideos v
join saImages i on i.sa_id = v.sa_id and i.picLinks = v.videoLinks
where v.sa_id=21;I usually avoid distinct/unique whereever possible. This requires the database to do a sort and makes the query slow.
Edited by: Sven W. on Feb 10, 2011 1:55 PM -
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
Maybe you are looking for
-
External screen turns green?
I've had this setup for a while now.. A 12 inch PB with a CRT 17 inch monitor connected to the PB through the "mini dvi to vga" adapter.. Now this is the problem: since a few days the image on my external screen is green.. It's not totally green, i c
-
HT1338 how do i update my iphone 3 without itunes
how do i update my iphone 3 with out itunes its giving me problems with updating it and i need the update in order to downlaod anything on it
-
Report execution without prompting user id
Hi, Is it possible to execute the report using Query designer/Web Application designer without prompting for User Id and password for selected queries? If possible, please let us know. Thanks in advance.
-
.rpt default setting Format not working?
I login to the administrator portal and right cilck on one of the report *.rpt and right click on it and properties, I see the default setting and format. So under format I choose format option, I choose Microsoft Excel 2003. and saved it. I then log
-
Not able to create confirmation
Hi Experts, While creating the confirmation in SRM 7.0 - EP, we are getting the error message as below "Process scheme not found" Please advice BR, Siva