Use distinct with decode
i use this
select count(distinct a.id_client) cant,
sum(decode(b.sex,'W',mount)) mount
from credit a,client b
where a.id_client = b.id_client
CANT MOUNT
11383 97305111.8
but if i want to use decode in the count, like this
select count(decode(b.sex,'W',distinct a.id_client)) cant,
sum(decode(b.sex,'W',mount)) mount
from credit a,client b
where a.id_client = b.id_client;
select count(decode(b.sex,'W',distinct a.id_client)) cant,
ERROR at line 1:
ORA-00936: missing expression
and if i use this query without distinct clause it work fine
select count(decode(b.sex,'W', a.id_client)) cant,
sum(decode(b.sex,'W',mount)) mount
from credit a,client b
where a.id_client = b.id_client;
CANT MOUNT
21668 97305111.8
what can i do, i want to get the quantity of clients by sex in diferents columns but i don't want to use a group by clause like this
select b.sex,count(a.id_client) cant
from credit a,client b
where a.id_client = b.id_client
group by b.sex
Try this.
SELECT COUNT(DISTINCT DECODE(b.sex,'W',a.id_client,null)) cant,
SUM(DECODE(b.sex,'W',mount)) mount
FROM credit a,client b
WHERE a.id_client = b.id_client;
Similar Messages
-
I want to count several categories(say a b c d) under same count and some catogories under another count ..there I need to use count with decode pls let me know the syntacs to write my query..this is ergent
regards
BuddhikeSomething like this ?
select count(decode(your_column,'a',1)) as "a",
count(decode(your_column,'b',1)) as "b",
count(decode(your_column,'c',1)) as "c",
count(decode(your_column,'d',1)) as "d"
from your_table;But maybe you can give us more details about what do you expected ?
Nicolas. -
Use DISTINCT with two fields to return one record
I am using OleDB with a SELECT DISTINCT query that is used in C# code to populate a DataGridViewComboBox. The queried table has two fields: ID and Description. The ID field values are unique. Descriptions may be duplicated. The DataSource of my DataGridViewComboBox
is ListBoxItems which is a ListBox that is populated from a table. The ValueMember is ID and the DisplayMember is Description. A sample table might look like this:
ID Description
1 Blue
2 Blue
3 Red
4 Blue
I want my query to return two records; one for the Red description and only one for the Blue description. I don't care which Blue description it returns, but I do need the corresponding ID for the selected Blue record and the ID value for the Red record.
Using SELECT DISTINCT ID, Description FROM... would give me four records instead of two. How can I return only two records in this scenario?
Rob E.Using window function:
create table #temp
ID int,
description varchar(20),
insert into #temp Values(1,'blue')
insert into #temp Values(2,'blue')
insert into #temp Values(3,'red')
insert into #temp Values(4,'blue')
;WITH CTE AS (select RN=ROW_NUMBER() OVER (PARTITION BY description ORDER BY newid() ),
ID,description from #temp)
SELECT ID, description from CTE
WHERE RN = 1;
ID description
4 blue
3 red
Kalman Toth Database & OLAP Architect
SQL Server 2014 Database Design
New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014 -
Using distinct with an Order by
Hi all,
I'm not an expert SQL coder and I've got stuck with the following issue.
I have a table named Workorder which contains a set of orders. Orders with status_id = 2 contain an error and this need to be re-submitted:
[ ID ] [WO_ID] [STATUS_ID]
1 10 2
2 10 1
3 20 2
So apparentely it seems very simple, however when orders are re-submitted things get complicated.
In the above query I need to pickup -just- the following row:
[ ID ] [WO_ID] [STATUS_ID]
3 20 2
The following row needs to be excluded from the list:
[ ID ] [WO_ID] [STATUS_ID]
1 10 2
Because the WO_ID has been later re-submitted successufully:
[ ID ] [WO_ID] [STATUS_ID]
2 10 1
So I need to pickup all workorders with a distinct on WO_ID ordered by ID desc, so that the distinct row contains just the highest ID (the latest order re-submitted).
I've tried in several ways, however I wasn't able to mix distinct + order by.
Maybe it can be done also in some other simpler ways ?
Thanks a lot
FrankSo, if the last ID for each WO_ID has STATUS_ID=2, that row needs to in the output.
But if the last ID has a different STATUS_ID, then that WO_ID is not to be in the output at all?
Perhaps this could work for you:
select
max(id) as id,
wo_id,
max(status_id) keep (dense_rank last order by id) as status_id
from workorder
group by wo_id
having max(status_id) keep (dense_rank last order by id) = 2
order by wo_idEdit:
Or an alternative using analytic functions:
select
id,
wo_id,
status_id
from (
select
id,
wo_id,
status_id,
last_value(status_id) over (
partition by wo_id
order by id
rows between unbounded preceding and unbounded following
) as last_status
from workorder
where last_status = 2If your workorder table actually contains several other columns you wish to select along with the id and status, then the analytic way can be much easier than a bunch of "keep" expressions ;-)
Edited by: Kim Berg Hansen on Nov 29, 2011 12:22 PM -
How to use distinct while using a select that builds xml?
Hi.
Example:
SELECT
XMLELEMENT("Column1" value1
,"Column2" value2
,"Column3" value3
FROM a_table A
Where id_val = x
Imagine that this repeats a same result 4 times. If it was a simple query distinct would work...how can i use distinct with this?
Thanks.
Cheers!Hi,
what about group by
SQL> WITH A AS(SELECT 1 val1,2 val2,3 val3 FROM dual UNION ALL
2 SELECT 1 ,2 ,3 FROM dual UNION ALL
3 SELECT 1 ,2 ,3 FROM dual)
4 SELECT XMLElement("cols"
5 ,XMLElement("col1",val1)
6 ,XMLElement("col2",val2)
7 ,XMLElement("col3",val3))
8 FROM A
9 GROUP BY val1,val2,val3;
XMLELEMENT("COLS",XMLELEMENT("COL1",VAL1),XMLELEMENT("COL2",VAL2),XMLELEMENT("CO
<cols><col1>1</col1><col2>2</col2><col3>3</col3></cols> -
SSRS reporting with sharepoint list using Distinct and Multivalue parameters
i want create ssrs report with sharepoint list using ms-vs(2008). i want create Distinct multivalue parameters by using CAML query. There is any way we put CAML query where we use Distinct keyword and IN clause in CAML query... i hope all experts will
understand my poor English... sorry for poor English.. plz help meHi AsifMehmood,
Per my understanding you have create an SSRS report with SharePoint list, now you don’t know to create the distinct parameters by using CAML query, right?
For the CAML language doesn’t have any reserved word (or tag) to set this particular filter to remove duplicate results, but we can use the custom code to do this function. I have tested on my local environment and we can do that by create one hidden parameter(Param1)
to get all the values from the fields which will add the filter and then create another parameter(Param2) to get the distinct values based on the Param1, we use the custom code to do the deduplication.
Step by Steps information in below thread for your reference to create the parameters and the custom code:
"How to get distinct values of sharepoint column using SSRS"
Other similar thread for your reference:
https://audministrator.wordpress.com/2014/02/17/sharepoint-list-add-distinct-parameter-value/
If your problem still exists, please feel free to ask and also try to provide us more details information.
Regards
Vicky Liu -
How can I use WM_CONCAT with DISTINCT in a stored provedure?
Hi,
I join three tables. For example one is for employees, other is for employee address, and the last one is for the cities of employees that work. I want to take the employee id, address city, and working cities. It is like the table below, but I want one line for each employee, so I used WM_CONCAT. Because there is duplicate data, I used DISTINCT in WM_CONCAT. It works fine normally, but if I want to use it in a stored procedure it gives an error :ORA-30482: DISTINCT option not allowed for this function. Is there anyone who could solve this problem? Thank in advance.
EXP_ID CITY_ADDRESS CITY_WORK
1 IZMIR IZMIR
2 IZMIR DENIZLI
2 IZMIR IZMIR
2 IZMIR IZMIR
Edited by: 878596 on 10.Ağu.2011 22:48WM_CONCAT is an undocumented function. It is used only for Oracle Internal Purpose. You are not supposed to use it. Never use any Undocumented feature of Oracle. That could get you into trouble.
Said that if you can tell us exactly what problem are you trying to solve with WM_CONCATE we could give you a better solution without using WM_CONCATE.
Please read the Link How to ask a question in this forum? To post the question in a proper way.
SQL and PL/SQL FAQ -
Query to find no of peoples with the same age(using distinct)
query to find no of peoples with the same age(using distinct)
Edited by: swordfish3 on Mar 7, 2009 9:24 PMit would be helpful if you posted some proper sample data with proper expected results.
The easier you make it for us to help you, the more likely you will get helped. -
Use sql function decode with Zend code
Hi,
I need to use sql function DECODE() in a query for PHP Code. This query works well in sql*plus but PHP returns
the following error message:
Parse error: syntax error, unexpected T_STRING in C:\Program Files\Zend\Apache2\htdocs\Compta\compta2.php on line 16
the query is :
$query =
'select substr(c.NUM,1 ,2) Compte ,
c.designation , a.Periode
,decode(substr(c.NUM,1 ,1), '1',1, '2',1,'3',1,-1) cp_type ,
sum(credit) - sum(debit) Montant
from ecritures a, clients b, compte c
where
b.NUM (+) =a.NUM
and a.DATEECRITURE between to_date(:debut, \'dd/mm/yy\') and to_date(:fin, \'dd/mm/yy\')
and substr(a.num,1,2) =c.num
group by substr(c.NUM,1 ,1), substr(c.NUM,1,2) , c.designation ,a.periode
order by compte ';
Can any one help me ???
Thanks by advance
nb: Iuse Zend 2.0Hi,
You need to escape single quote mark:
decode(substr(c.NUM,1 ,1), \'1\',1, \'2\',1,\'3\',1,-1) cp_type ,
the same way you did for to_date:
to_date(:debut, \'dd/mm/yy\')
Regards,
Paweł -
Error while replacing IF statements with DECODE function in procedure
Hi All,
I have created a procedure which has nested IF statements. Now I want to replace the IF statements with DECODE functions to improve performance.
Procedure:
IF (var_int_sev = '0')
THEN
var_sev := '2';
ELSE
SELECT sev
INTO var_int_sev
FROM errorconfig
WHERE errorcode = var_errorcode;
var_sev := var_int_sev;
END IF;
I converted the above IF statement into DECODE function as mentioned below:
var_Sev := DECODE(var_int_sev,0,2,SELECT severity FROM errorconfig WHERE errorcode=var_ErrorCode)
But it throws below error at the select statement used inside DECODE.
Error(58,51): PLS-00103: Encountered the symbol "SELECT" when expecting one of the following: ( - + case mod new not null others <an identifier> <a double-quoted delimited-identifier> <a bind variable> avg count current exists max min prior sql stddev sum variance execute forall merge time timestamp interval date <a string literal with character set specification> <a number> <a single-quoted SQL string> pipe <an alternatively-quoted string literal with character set specification> <an alternativ
Can someone help me in converting the IF to DECODE in the above case. Also how can we use a select statement inside decode.instead of trying to rewrite all your code and hoping that the performance will be better, it's a better option to investigate and find out which part of your application is slow
read this:
When your query takes too long ... -
Problem with DECODE block in WHERE clause
Hi,
I'm facing problem with DECODE statement. I just simulated my problem in the simple way as follows. If I execute this following query, I should get "hello", but I'm not getting anything (ZERO rows returned).
SELECT 'hello' FROM DUAL
WHERE 'sample1' in (DECODE(1, 1, '''sample1'', ''sample2'', ''sample3''',
2, '''sample4'', ''sample5'', ''sample6'''
I think some problem is there in my WHERE clause.
But When I'm exeucting the following query as a seperate query, then I'm getting the value of DECODE block properly, but didn;t understnad why its not returning the same way when I'm putting the same DECODE statement in WHERE clause.
SELECT DECODE(1, 1, '''sample1'', ''sample2'', ''sample3''',
2, '''sample4'', ''sample5'', ''sample6'''
FROM DUAL;
Please help me to get out of this problem. Thank you so much in advance.
Thanks,
Ramji.The value returned by SELECT DECODE(1, 1, '''sample1'', ''sample2'', ''sample3''',2, '''sample4'', ''sample5'', ''sample6''') FROM DUAL;
'sample1', 'sample2', 'sample3' is a single string. Consider it x.
SELECT 'hello' FROM DUAL WHERE 'sample1' in ( DECODE(1, 1, '''sample1'', ''sample2'', ''sample3''',2, '''sample4'', ''sample5'', ''sample6'''));
is like SELECT 'hello' FROM DUAL WHERE 'sample1' in ('x');
or
SELECT 'hello' FROM DUAL WHERE 'sample1' in ('''sample1'', ''sample2'', ''sample3''') and not
SELECT 'hello' FROM DUAL WHERE 'sample1' in ('sample1', 'sample2', 'sample3');
For this same reason SELECT 'hello' FROM DUAL WHERE 'sample1' in (select '''sample1'', ''sample2'', ''sample3''' from dual);
also does'nt work.
Please use INSTR to find whether 'sample1' exists in the string 'sample1', 'sample2', 'sample3'. -
Problems with decoding an latin1-encoded url
Hi,
i have a problem with decoding german umlaut-characters from an URL.
I'm using Tomcat 5.5 on a Linux server and one on a windows machine for development. Both webapps have the same configurations.
A servlet decodes the URL-String, parses it and stores the parsed data into a mysql-DB.
For decoding the query-string i'm using org.apache.commons.codec.net.URLCodec.URLCodec.decode .
Here's the code:
String unparsedParameters = request.getQueryString();
URLCodec codec = new URLCodec("ISO-8859-1");
result = codec.decode(unparsedParameters);Here an example for a query-string: http://servername:8080/servlet/Import?Etwas%20wurde%20am%2025.08.2010%2010%3A16%3A50%20*ge%E4ndert*
On the windows machine the word "*geändert*" is decoded correctly. But on the linux server i get "*ge?ndert*". It makes no difference if i write the result into the database or just into a logfile.
Can anyone help?
Thanks in advance.
Edited by: sol1640 on Aug 26, 2010 5:59 AMProblem resolved.
Instead of using the decode-method as described in my fist message now i'm doing the folowing:
fURLDecodigCharset = "ISO8859-1";
byte[] bytes = originalParam.getBytes(fURLDecodigCharset);
byte[] decodeUrl = URLCodec.decodeUrl(bytes);
result = new String (decodeUrl, fURLDecodigCharset);because the method "decode" decodes the string by using the defaultcharset. And that was the problem.
>
The default charset is determined during virtual-machine startup and typically depends upon the locale and charset of the underlying operating system.
>
Thats why i've got different behaviours on different systems.
Thanks -
Using distinct and orderby in the select statment
Hi All,
Can anyone tell me what is the purpose of using distinct and orderby in the select statment.Hi,
Using the distinct function with more than one column yields some substantial results. SQL will return the rows with distinct or unique combinations of those columns. Assume this same employee table has another column including the salary of each employee. With the use of the distinct function we can pull a list of unique job titles - salaries.
SQL Code:
SELECT DISTINCT job_titles, salary FROM employees;
SQL has returned all the rows with unique combinations of job titles and salaries. Any duplicate combinations of job titles and salaries will be ignored. For example if we had two CEOs in the table making the same salary each year, only one row would be returned but if we had two CEOs with different salaries, both rows would be returned.
Order by
The SQL ORDER BY clause comes in handy when you want to sort your SQL result sets by some column(s). For example if you want to select all the persons from the already familiar Customers table and order the result by date of birth, you will use the following statement:
SELECT * FROM Customers
ORDER BY DOB
As you can see the rows are sorted in ascending order by the DOB column, but what if you want to sort them in descending order? To do that you will have to add the DESC SQL keyword after your SQL ORDER BY clause:
SELECT * FROM Customers
ORDER BY DOB DESC
If you don't specify how to order your rows, alphabetically or reverse, than the result set is ordered alphabetically, hence the following to SQL expressions produce the same result:
SELECT * FROM Customers
ORDER BY DOB
SELECT * FROM Customers
ORDER BY DOB ASC
You can sort your result set by more than one column by specifying those columns in the SQL ORDER BY list. The following SQL expression will order by DOB and LastName:
SELECT * FROM Customers
ORDER BY DOB, LastName
if its useful reward points -
Using function on decode or case in query
Hi experts
I am using oracle 11G database,I have to check length of name column value from employee table and if length(name) > 39 then value should be substr(name,0,39)
else value should be name only.
i tried below code
select CASE when length(name) > 39,substr(name,0,39)
else name
END
from employee but its not working ..can I do this using decode too ? ,,which one would be better or this is not a right way ?
ThanksHi,
siebelD wrote:
Hi experts
I am using oracle 11G database,I have to check length of name column value from employee table and if length(name) > 39 then value should be substr(name,0,39)
else value should be name only.
i tried below code
select CASE when length(name) > 39,substr(name,0,39)
else name
END
from employee but its not working ..Review the syntax of the CASE expression in the SQL Language manual. A CASE expression always has at least one THEN clause. Commas are not part of the CASE expression syntax.
can I do this using decode too ? Sure, anything you can do with CASE you can also do with DECODE.
,,which one would be betterThis is one of the many situations where CASE is much shorter, clearer and more efficient than DECODE.
or this is not a right way ?How about
SELECT SUBSTR (name, 1, 39) AS employee_name
FROM employee;?
If name is 39 characters (or less), then <tt> SUBSTR (name, 1, 39) </tt> will return it, unchanged.
Edited by: Frank Kulash on Mar 3, 2013 2:07 PM -
OWB3i - Validate with DECODE function
Hi,
in OWB 3i when I validate an expression defined inside an expression operator with DECODE() function (which is not include in default transformation) come this error:
Line 1, Col 1:
PLS-00204: function or pseudo-column 'DECODE' may be used inside a SQL statement only
but it seems only a warning because when i generate the scripts and run no other error happen and all works fine.
RegardsHi,
Welcome to the forum!
When you use a default value, the last argument to DECODE is the actual value you want as a default.
For example:
SELECT ename
, deptno
, DECODE ( deptno
, 30 , 'Sales'
, 'All others' -- Default value
) AS dname
FROM scott.emp
ORDER BY ename
;Output:
ENAME DEPTNO DNAME
ADAMS 20 All others
ALLEN 30 Sales
BLAKE 30 Sales
CLARK 10 All others
FORD 20 All others
JAMES 30 Sales
JONES 20 All others
KING 10 All others
MARTIN 30 Sales
MILLER 10 All others
SCOTT 20 All others
SMITH 20 All others
TURNER 30 Sales
WARD 30 Sales
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
Explain, using specific examples, how you get those results from that data.
If you can show the problem using commonly available tables (such as those in the scott schema) then you don't need to post any sample data; just the results and the explanation.
Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
See the forum FAQ {message:id=9360002}
Maybe you are looking for
-
Dropdown boxes do not work on Firefox 5.0.
When using the address bar or any dropdown box on Firefox, the drop down menu flashes but will not stay open so that I can use it. I do not have this issue in IE. I have started Firefox in Safe Mode and the dropdown boxes still did not work. I can't
-
using bootcamp, was installing windows xp, at the select ntfs or fat format mistakenly selected "leave the current file system intact." How can that be changed to a correct choice. Mac side opens correctly. Windows shows disk error. and doesn't respo
-
If I get the APP & send in my iPod b4 the second year,do I have to pay s&h?
I got my 5th gen iPod last May and the battery is already dead. I haven't gotten the AppleCare Protection Plan (APP) yet but if I get it and then send my iPod in for a new battery directly after I start my APP(before the second year starts), do I sti
-
ValueEx versus Value (Matrix UserDataSource)
If I add a new line to a Matrix and clear the value of a number column using : dsQuantity.ValueEx = ""; I receive this error Data Source - Invalid field value [66000-19] However, I can successfully clear the column's cell using the method of Value (
-
Can't you use all Arithmetic operators with characters?