Sunday, March 25, 2012

count distinct

Hi... hereby i hv a problem

At my database, I hv a field "component_detail_key",
and the data is :
T002811_1
T002811_2
T002812_1
T002812_2
T002813_1
T002813_2

I get the data before _ :
T002811
T002811
T002812
T002812
T002813
T002813

Now I hv to count distinct, the output should be 3.
I use 2 for loop in this function but can't do that.
Below is my coding :

int distinct = 0;

for (int i = 1; i < a; i++){
for (int j = 1; j < a; j++)
{
if (swkey[i]==swkey[j])
{
distinct = distinct;
} else {
distinct ++;
}
} // End for
}

The answer is :5 , 10 , 15 , 20 , 25 , 30

Anyone can help?pls~Why don't you just do this in SQL something like this:

SELECT COUNT( DISTINCT( SUBSTR( code, 1, INSTR(code,'_')-1 )))
FROM table
...;

I'm using Oracle SUBSTR and INSTR functions, but most DBMSs have something similar.|||May I know what is the meaning for :INSTR(code,'_')-1?
The "code" is field or...?

Thx~|||INSTR(string1, string2) returns the position of string2 within string1. Therefore, SUBSTR(string1, 1, INSTR(string1, string2)-1) will return a new string containing all the chacracters of string1, prior to the occurence of string2.

Example,

String1('123456');
String2('4');

SUBSTR(string1, 1, INSTR(string1, string2)-1) = "123"|||oh i c~
Thanks very much!!!|||BUt still hv error : invalid command for INSTR...
I am using jsp... is it can't support this code?|||I would recommend that the DBMS perform the complete operation.

Java:
IndexOf(string)|||sorry not understand this.....
I am fresh with Java

is it
String sqlsw = "SELECT SUBSTRING_INDEX(component_detail_key, '_', 1) AS sw FROM component_detail WHERE component_key=?";
?
but still can't...|||I solve the problem by CHARINDEX,
thx very much for your help :)

No comments:

Post a Comment