SELECT DISTINCT with LINQ
Hey,
I am trying to perform a SELECT DISTINCT COL1, COL2, COL3 FROM VIEW WHERE CONDITION using LINQ with ODAC 112030 but I get different results.
C#:
var s1 = context.Select(v=>new { v.COL1, v.COL2, v.COL3}).Where(...).Distinct();
Any ideas?
Hey,
I think this way works - with anonymous types:
context.Entity.Where(...).Select(ent => new { col1 = ent.COL1, ... }).Distinct();.
You can also do context.Entity.Select("distinct it.COL1, it.COL2").Where("..."); but one should be careful to add all necessary columns in select statement.
Edited by: 917334 on Jun 7, 2012 7:11 AM
Similar Messages
-
Need help with select distinct with group by
RDBMS 10gr2
I am trying achieve having a select distinct with a order by and after looking on the internet and trying different examples, I have been unsucessful.
Here is the code working (not sorting - I wish to sort by pps.last_name however I can't seem to get it to work).
select distinct pps.last_name || ', ' ||pps.first_name || ' ' ||pps.middle_initial || '.' d,
emple_no r
from cobr.vw_pps_payroll pps,
projman pm
where term_date is null
and department = '0004400000'
and pm.eid != pps.emple_noSQL> SELECT ename || '-' || empno, sal
2 FROM emp_test
3 ORDER BY ename;
ENAME||'-'||EMPNO SAL
BLAKE-7698 20000
CLARK-7782 20000
DAVID-7699 20000
FORD-7902 6000
JONES-7566 5950
KING-7839 10000
SCOTT-7788 6000
7 ligne(s) sélectionnée(s).
SQL> -
SELECT DISTINCT With OPEN cursor FOR
Hello.
I have the following procedure. All it does is open a cursor for an SQL string passed into it, and return the open cursor.
PROCEDURE sp_execute_dynamic (hold_input_string IN CLOB,
hold_cursor OUT hold_cursor_type) IS
BEGIN
OPEN hold_cursor FOR TO_CHAR(hold_input_string);
END sp_execute_dynamic;
It works fine except when I perform SELECT DISTINCT. I get the following error.
SQL> declare
2 TYPE hold_cursor_type IS REF CURSOR;
3 hold_cursor hold_cursor_type;
4 hold_object_name VARCHAR2(1024);
5 hold_object_type VARCHAR2(1024);
6 begin
7 dynamic_sql_pkg.sp_execute_dynamic('select distinct object_name from user_objects where object_
name in (''PLAN_TABLE'',''DBA_OBJECTS'')',hold_cursor);
8 loop
9 fetch hold_cursor into hold_object_name, hold_object_type;
10 exit when hold_cursor%NOTFOUND;
11 dbms_output.put_line('Object Name = '||hold_object_name||' Object Type = '||hold_object_type);
12 end loop;
13 end;
14 /
declare
ERROR at line 1:
ORA-01007: variable not in select list
ORA-06512: at line 9
It does the same thing with SELECT UNIQUE or SELECT with a GROUP BY. Can anyone tell me why this happens and what I could to to work around it?
Thanks
Chrissee at line 7 you are selecting only one column and at line 9you are fetching into two variables
7 dynamic_sql_pkg.sp_execute_dynamic('select distinct object_name from user_objects where object_
name in (''PLAN_TABLE'',''DBA_OBJECTS'')',hold_cursor);
8 loop
9 fetch hold_cursor into hold_object_name, hold_object_type;
HTH -
Hi,
how Do I write this select in rigth way in ABAP
SELECT ska1ktopl AS ktopl ska1saknr AS saknr
t370k_t~eartx AS eartx
INTO TABLE lt_ska1 FROM ska1
JOIN (SELECT DISTINCT damage_gl FROM zzpm_cost_elem ) ON ska1saknr = zzpm_cost_elemdamage_gl.
The problem with the select "SELECT DISTINCT damage_gl FROM zzpm_cost_elem " which I have to put table name instead of it
What should I do ?
ThxHi Friend ,
Please see this example how you can use the select DISTINCT statement
DATA: ITAB TYPE STANDARD TABLE OF SPFLI,
WA LIKE LINE OF ITAB.
DATA: LINE(72) TYPE C,
LIST LIKE TABLE OF LINE(72).
LINE = ' CITYFROM CITYTO '.
APPEND LINE TO LIST.
SELECT DISTINCT (LIST)
INTO CORRESPONDING FIELDS OF TABLE ITAB
FROM SPFLI.
IF SY-SUBRC EQ 0.
LOOP AT ITAB INTO WA.
WRITE: / WA-CITYFROM, WA-CITYTO.
ENDLOOP.
ENDIF.
Regards, -
Ho to do a select distinct with many colums
Hi,
How can I do a select distinct from many colums so that I get only one result for each case.
e.g if I want to select from employees table.
Hire_date,salary,job_id,department_idThis could be one of the solutions !
SQL> SELECT * FROM DS;
DEPTNO JOB ID
101 MANAGER 500
101 ANALYST 520
105 ANALYST 520
101 MANAGER 501
102 MANAGER 501
102 PROGRAMMER 605
102 PROGRAMMER 501
103 CLERK 605
8 rows selected.
SQL> select case when row_number() over(partition by deptno order by deptno)>1
2 then null else deptno end "DEPTNO",
3 case when row_number() over(partition by job order by job) >1
4 then null else job end "JOB",
5 case when row_number() over(partition by id order by id )>1
6 then null else id end "ID" from ds;
DEPTNO JOB ID
101 ANALYST 520
MANAGER 500
501
102
605
PROGRAMMER
103 CLERK
105
8 rows selected. -
Select distinct using LINQ and bound to a dropdown list with id and display name
Hi,
On one of my sharepoint page, I want to populate dropdown list with countries, namely
<asp:DropDownList ID="ddlCountry" runat ="server"></asp:DropDownList>
In the code, I use LINQ:
var country = (from p in dc.ProvCountries
select p.country_code ).Distinct();
ddlCountry.DataSource = country;
ddlCountry.DataBind();
I want the country_code to be the ID, while the country_name will be the display name in the dropdown, how can that be done?
Thanks in advance.Hi,
The following code for your check.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplicationLib
public partial class _Default : Page
protected void Page_Load(object sender, EventArgs e)
List<ProvCountries> list = new List<ProvCountries>();
list.Add(new ProvCountries { country_code = "201", country_name = "A"});
list.Add(new ProvCountries { country_code = "201", country_name = "B" });
list.Add(new ProvCountries { country_code = "202", country_name = "C" });
list.Add(new ProvCountries { country_code = "202", country_name = "D" });
var country = (from p in list select new { p.country_code, p.country_name }).DistinctBy(p => p.country_code).ToList();
ddlCountry.DataSource = country;
ddlCountry.DataValueField = "country_code";
ddlCountry.DataTextField = "country_name";
ddlCountry.DataBind();
ddlCountry.Items.Insert(0, new ListItem("Please select", ""));
class ProvCountries
public string country_code { get; set; }
public string country_name { get; set; }
static class DataDistinct
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
if (seenKeys.Add(keySelector(element)))
yield return element;
Thanks,
Dennis Guo
TechNet Community Support
Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
[email protected]
Dennis Guo
TechNet Community Support -
Help! Howto use the join function in a query with select distinct ?
Hi!
I have 2 tables. I want to select only 1 painting of each artists.
select distinct idartist
from tbl_artworks
where blah blah blah
order by rand()
how does the "join" function work for add: name, lastname, title, image and much more... i try... but i fail...
tbl_artists
idartist
name
lastname
1
Paul
Gaugain
2
Vincent
Van Gogh
3
Pablo
Picasso
tbl_artworks
idartwork
idartist
title
image
1
1
days of gods
image1.jpg
2
2
sunflower
image2.jpg
3
3
Dora maar au chat
image3.jpg
4
2
Sky
image4.jpg
5
3
La vie
image5.jpgGetting a single random image for each probably requires a combination of sql and cf. It would take someone smarter than me to do it with sql alone. I would probably try something like this:
1. Run a database query that gets all the images from all the artists.
2. Run a Q of Q that gets a distinct list of artist ids.
3. Loop through that list and run a Q of Q to get all the images for that artist.
4. Still in that loop, use randrange (1 to the recordcount) to select a random record from your Q of Q -
Select distinct problem with muliple join tables, help needed
Hi,
I have two main tables. Each has its of sub joined tables.
guest_id_for_reservation connects two major tables. This has
to be that way
because my guest may change the room status from single to
double (and the
similar exceptional requests).
guests reservation
guest_id_for_reservation
countrytable hoteltable
delegationtable roomtype
I form a query. I want to select distinct those results. But
it does not
work.
If I do not include any table related to reservation table
and its sub
joined tables (disregarding guest_id_for_reservation), it
works.
Is there a specific syntax for select distinct of this type
or any
workaround.?
Thank you
HakanHi I'm still battling with this - have connected the AX to my Imac via ethernet and it shows up fine in Airport Utility. Status light is green and it says its set up to connect to my existing wireless network using wireless connection. Security in Network Preferences is the same for both: WPA2 Personal.
So I don't think there's a problem with the AX, and my current wireless network (BT Home Hub) is working fine.
And when I restore factory settings Airport Utility can see the AX before updating settings so the wireless side of AX must work too.
I'm figuring it must be something about the settings that mean AU can't see it anymore. But I can't work out what, since security is the same.
Any ideas would be great! -
Problems with "Select Distinct" Statement
Hi... I've a little problem with my SQL Statement...
I've a Table in a DataBase with Solds of the Month... the fields are: vta_fecha, vta_prod, vta_total, vta_mesa.
I've to Select only the distincts fields of vta_prod... selected by vta_fecha and vta_mesa...
My code is like this: try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conec = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=C:/POOL/Data/BaseDat.MDB");
state = conec.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);try{
rec = state.executeQuery("Select DISTINCT vta_prod, vta_fecha, vta_mesa from Ventas where vta_fecha = #" + Fecha_q + "# And vta_mesa = 0");
rec.first();
int x = 0;
while (rec.isAfterLast()==false){
x++;
rec.next();
rec.first();
if (x > 0){
Productos = new String[x];
Total_Vta = new int[x];
Cant_Prod = new int[x];
x = 0;
while (rec.isAfterLast() == false){
Productos[x] = rec.getString("vta_prod");
rec.next();
x++;
else{
Productos = new String[0];
Total_Vta = new int[0];
Cant_Prod = new int[0];
}catch(Exception e){JOptionPane.showMessageDialog(null,e.getMessage());}Now, in the Table I have only 3 diferents vta_prod, but this Statement returns 9 Rows... and I don't know why...
Please help me...
Regards...I don�t have a complete picture because I don�t know what values you are passing in the select and I don�t know your column types but this is what I think is happening from what you have shared.
You may have misunderstood what the DISTINCT keyword does.
The DISTINCT keyword applies to the full set of columns in the select (not just the first column). So in your case it would be equivalent to:
SELECT vta_prod, vta_fecha, vta_mesa
FROM Ventas
WHERE ...
GROUP BY by vta_prod, vta_fecha, vta_mesa
So, it doesn't matter that you only have 3 distinct vta_prod values if you have multiple values being returned in the other columns. The vta_mesa column can only a return a single value as �0�. That leaves the vta_fecha column which is probably a date/time column and is probably the column that is returning the three other distinct values (one date with three distinct times).
(3 vta_prod) x (3 vta_fecha) x (1 vta_mesa) or 3x3x1 = 9 rows
So find a way to strip the time from vta_fecha in your select statement and your SQL should return the results you expect. I�m not an Access expect but I think I remember you can use something like the �Convert� or �DatePart� functions to make that happen (check your documentation to be sure)..
A couple of asides;
1) You should use a PreparedStatement and rarely if ever use Statement.
2) You should start Java variable names with lower case. -
Select distinct statement with various alias
Hi everybody,
I'm trying to put a select distinct statement in a query with two different alias for two different tables; like that:
select distinct a.ma_name||'.'||a.ma_first_name d,
a.ma_first_name||'.'||a.ma_name r
from ma_main a, manager_liste b
where (UPPER(b.manager_first_name||'.'||b.manager_name) = :APP_USER or
(case when 'X'=:APP_USER or 'Y'=:APP_USER
then 1
else 0
end) = 1)
order by a.ma_name
But it doesn't work. Can anybody help?
Thx a lot!
Janhi,
this is the error:
1 error has occurred
LOV query is invalid, a display and a return value are needed, the column names need to be different. If your query contains an in-line query, the first FROM clause in the SQL statement must not belong to the in-line query.
and the table manager_liste and ma_main are varchar tables.
how can i make it work, so that my select list with submit does only show distinct names. Because right now it shows each name about 10 times.... -
"connect by" problem with "select distinct"
When I run the following SQL (using "Scott" DB):
select *
from emp
where deptno = 30 or mgr is null
start with mgr is null
connect by prior empno = mgr
order siblings by ename
I get the results one would expect. The President is first and all those reporting to him/her are listed in correct sequence.
EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO
7839,KING,PRESIDENT,,11/17/1981,5000,10
7698,BLAKE,MANAGER,7839,5/1/1981,2850,30
7499,ALLEN,SALESMAN,7698,2/20/1981,1600,300,30
7900,JAMES,CLERK,7698,12/3/1981,950,30
7654,MARTIN,SALESMAN,7698,9/28/1981,1250,1400,30
7844,TURNER,SALESMAN,7698,9/8/1981,1500,0,30
7521,WARD,SALESMAN,7698,2/22/1981,1250,500,30
However, when I run the same query but make it "select distinct" I get the following:
EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO
7499,ALLEN,SALESMAN,7698,2/20/1981,1600,300,30
7698,BLAKE,MANAGER,7839,5/1/1981,2850,,30
7900,JAMES,CLERK,7698,12/3/1981,950,,30
7839,KING,PRESIDENT,,11/17/1981,5000,,10
7654,MARTIN,SALESMAN,7698,9/28/1981,1250,1400,30
7844,TURNER,SALESMAN,7698,9/8/1981,1500,0,30
7521,WARD,SALESMAN,7698,2/22/1981,1250,500,30
Why would adding "distinct" to the select cause the result to be sorted STRICTLY by ename (per "order siblings by...")?
Finally, if I "select distinct" but don't specify any "order" I get this, in NO APPARENT order:
EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO
7499,ALLEN,SALESMAN,7698,2/20/1981,1600,300,30
7521,WARD,SALESMAN,7698,2/22/1981,1250,500,30
7654,MARTIN,SALESMAN,7698,9/28/1981,1250,1400,30
7698,BLAKE,MANAGER,7839,5/1/1981,2850,,30
7839,KING,PRESIDENT,,11/17/1981,5000,,10
7844,TURNER,SALESMAN,7698,9/8/1981,1500,0,30
7900,JAMES,CLERK,7698,12/3/1981,950,,30
Thanks in advance for any insight offered!
-Geneyou have to specify what is going to be the distict field.No you don't. DISTINCT keyword applies to the whole SELECT list. See your own link.
In any case this does not appear to have anything to do with what you SELECT, rather that the SORT UNIQUE caused by the DISTINCT keyword appears to prevent the ORDER SIBLINGS BY clause from working correctly.
Not really sure why you need DISTINCT in this example, no doubt this is being applied elsewhere. Given that you have duplicates in the rowset and that hierarchical query now supports views, perhaps it would be more efficient to apply DISTINCT keyword first, something like...
SELECT e.*
FROM (SELECT DISTINCT e.*
FROM emp e
WHERE e.deptno = 30
OR e.mgr IS NULL) e
START WITH e.mgr IS NULL
CONNECT BY PRIOR e.empno = e.mgr
ORDER SIBLINGS BY e.ename;
Alternatively you could skip ORDER SIBLINGS BY clause and use SYS_CONNECT_BY_PATH function to get your order, something like...
SELECT e.*
FROM (SELECT DISTINCT e.*,
SYS_CONNECT_BY_PATH () path
FROM emp e
WHERE e.depno = 30
OR e.mgr IS NULL
START WITH e.mgr IS NULL
CONNECT BY PRIOR e.empno = e.mgr) e
ORDER BY e.path
Padders -
OraException from Command.ExecuteReader with SELECT DISTINCT
Hello
I am trying to fill an OraDataReader object from a OraCommand object.
It appears that whenever the statement includes a SELECT DISTINCT, the command fails (even though the SQL statement works fine when executed e.g. in TOAD)
Dim Conn As OraConnection = New Oracle.DataAccess.Client.OraConnection("[Valid connection string]")
Conn.Open()
Dim Command As OraCommand = New OraCommand()
Command.CommandType = CommandType.Text
Command.CommandText = "select DISTINCT nvl(SUBFAMILY_COMPETENCY_ID, 0) SUBFAMILY_ID, nvl(NAME, ' ') NAME, FAMILY_COMPETENCY_ID FAMILY_ID " & _
" from TAXONOMY_RELATIONAL, COMPETENCY " & _
" where TAXONOMY_RELATIONAL.CL_ID = :1 " & _
" AND COMPETENCY.cl_id (+) = TAXONOMY_RELATIONAL.cl_id and COMPETENCY.language_id (+) = :2 " & _
" and COMPETENCY.COMPETENCY_ID (+) = TAXONOMY_RELATIONAL.SUBFAMILY_COMPETENCY_ID " & _
" order by FAMILY_ID, SUBFAMILY_ID"
Command.Parameters.Add("@CL_ID", context.Session!CLID)
Command.Parameters.Add("@LANGUAGE_ID", context.Session!LANGUAGEID)
Dim DataReader As OraDataReader = Command.ExecuteReader(CommandBehavior.CloseConnection)
An Oracle.DataAccess.Client.OraException is raised when executing the last statement, but no further details are given in the error message. The stack trace begins as follows
[OraException]()
Oracle.DataAccess.Client.OraException.HandleErrorHelper(Int32 errCode, OraConnection conn, IntPtr opsErrCtx, IntPtr opsSqlCtx, Object src, String procedure) +639
Oracle.DataAccess.Client.OraCommand.ExecuteReader(+737)
Oracle.DataAccess.Client.OraCommand.ExecuteReader(CommandBehavior behavior) +8
The exception disappears as soon as I remove the DISTINT keyword from my SQL statement.
Is this a bug or am I doing something wrong?
Thanks for help,
Bernt FischerThis issue is same as the one mentioned in the thread with title "Problem with 'Select distinct'" and the fix would be available in the next release.
-
Issue with "Select Distinct" query in Oracle 10g against Oracle 9i
Hi,
I would appreciate if some one help me here because it is really urgent.
We are upgrading our database from 9i to 10g.
There are the "Select distinct" queries in the code which populated the grid on the applications screens. We found a difference in 9i and 10g the way the result is populated for these queries. If "Select Distinct" query wihtout a order by clause is executed in 9i then the result is automatically sorted. But Oracle 10g does not do this.
We can change the queries adding order by clause but we are almost at the end of the testing and want to know if there is any way that we can do this from database settings. Would there be any impact of these settings change on overall operation of Oracle 10g?
I would appreciate if some one can help me here.
Thanks,
Dineshthen the result is automatically sorted.No. Oracle may have done a sort operation to perform the distinct, but it still did not guarantee the order of your results.
In 10g and in 9i, if you want your results in a certain order you must use order by. -
Something´s going wrong with select distinct (Oracle 10g)
Our database is oracle 10g release 2 and the query statement is:
select distinct last_name
from students;
and the query returns all of the last_names without an specific order..
If I execute the same query in oracle 9i the query returns all of the last_name in alphabetic order.
Why is it different on Oracle 10g?See also this blog entry from Mr. Kyte.
C. -
Query help in select Distinct on one column.
CREATE GLOBAL TEMPORARY TABLE Table1 (
ID1 varchar2(100) ,
Name1 varchar2(100),
Name11 varchar2(100)
insert into Table1 values ('a','n1','h3');
insert into Table1 values('b','n2','h2');
insert into Table1 values('a','n3','h1');
insert into Table1 values('c','n4','h5');
insert into Table1 values ('c','n5','h4');
insert into Table1 values('d','n6','h6');
select * from Table1;
ID1,NAME1, NAME11
a, n1, h3
b, n2, h2
a, n3, h1
c, n4, h5
c, n5, h4
d, n6, h6
I am trying to select distinct ID1 and all values associated with it which is max row.I want to result as -
ID1,NAME1, NAME11
a, n3, h1
b, n2, h2
c, n5, h4
d, n6, h6
Can you please help me to write simple query to get above result.
Edited by: 871447 on Jul 25, 2011 9:42 AM
Edited by: 871447 on Jul 25, 2011 9:45 AMHi,
Do a self-join, to combine the two rows for each value of id1 onto one output row.
Make it an outer join, in case there is only one row with a vlaue for id1.
SELECT l.id1
, l.name1
, NVL ( r.name11
, l.name11
) AS name11
FROM table1 l
LEFT OUTER JOIN table1 r ON l.id1 = r.id1
AND l.name1 < r.name1
;Edited by: Frank Kulash on Jul 25, 2011 12:57 PM
Sorry, I mis-read the problem.
Lee's solution, above, assumes that name1 is unique, as it is in your sample data.
What output would you want if that's not the case?
If name1 is not unique, but the combination of (id1, name1) is unique, then you can modify Lee's solution like this:
SELECT *
FROM table1
WHERE (id1, name1) IN (
SELECT id1
, MAX (name1)
FROM table1
GROUP BY id1
;Or, if you can't make any assumptions about uniqueness, you might need something like this:
WITH got_r_num AS
SELECT id1, name1, name11
, ROW_NUMBER () OVER ( PARTITION BY id1
ORDER BY name1 DESC
, name11 DESC
) AS r_num
FROM table1
SELECT id1, name1, name11
FROM got_r_num
WHERE r_num = 1
;
Maybe you are looking for
-
Motion blur issue once exported to DVD through Encore
I have 59.94 HD footage. I edit it, export it through Adobe Media Encoder to Mpeg-2 DVD at 29.97, drop-frame, lower field dominance. I then import that .m2v file into Encore, and then export to DVD, without re-transcoding or encoding anything. The DV
-
Sap script creation for SO & PO
external subroutine creation for displaying Sales Order & Purchase Order scheduling details in the SAP script.
-
Wordpress Development in DW CS6 (non-default permalinks)
I'm running Dreamweaver CS6 on Mac OS X Mountain Lion. I have MAMP installed and running. I'm developing a Wordpress-based web site, but I've been unable to set up a local testing server because, for a number of reasons - including the fact that th
-
Funny red icon next to unsent text messages - what's this about?
Help! BB (Curve 8520)stopped sending texts today and a little red icon (letter L within a red circle) comes up by unsent texts. Cannot see what has changed,or why it's happened and most importantly cannot rectify it! Any thoughts, views or advice wou
-
T510: Upgrade from i5 to i7?
Hi all, I have lenovo ThinkPad T510(Type:4314-4PG). Is it possible for me to upgrande processor from i5 520M to i7 820QM? I have installed i7 820qm to motherboard but notebook not work. Power led on but cooler and display is not.... Solved! Go to So