Trying To Add A NON-DISTINCT Field To A DISTINCT Record Set In A Query.

Mar 12, 2007

I need to run a SELECT DISTINCT query across
multiple fields, but I need to add another field that is NON-DISTINCT
to my record set.

Here is my query:


SELECT DISTINCT lastname, firstname, middleinitial, address1,
address2, city, state, zip, age, gender
FROM gpresults
WHERE age>='18' and serviceline not in ('4TH','4E','4W')
and financialclass not in ('Z','X') and age not in
('1','2','3','4','5','6','7','8','9','0')
and (CAST (ADMITDATE AS DATETIME) >= DATEDIFF(day, 60, GETDATE()))
ORDER BY zip


This query runs perfect. No problems whatsoever. However, I need to
also include another field called "admitdate" that should be treated
as NON-DISTINCT. How do I add this in to the query?


I've tried this but doesn't work:


SELECT admitdate
FROM (SELECT DISTINCT lastname, firstname, middleinitial, address1,
address2, city, state, zip, age, gender from gpresults)
WHERE age>='18' and serviceline not in ('4TH','4E','4W')
and financialclass not in ('Z','X') and age not in
('1','2','3','4','5','6','7','8','9','0')
and (CAST (ADMITDATE AS DATETIME) >= DATEDIFF(day, 60, GETDATE()))
ORDER BY zip


This has to be simple but I do not know the syntax to accomplish
this.


Thanks

View 2 Replies


ADVERTISEMENT

DISTINCT SELECT Query With More Than One Field

Feb 6, 2008

Hello, I want to do a DISTINCT  SELECT query with more than one field, for example a ID field with a Type field, as if both fields make the primary key, like (ID 1 ,Type 1) ,( ID 1, Type 2) and (ID 2, Type 1) is ok but not (ID 1, Type1) and (ID 1,Type 1) if its not possible to do a distinct with more than one then what other techniques are possible to get the duplicate data out.   the reason why I want to use distinct is that I can use that query to export that data to where both of these fields make the primary key.
Thanks in advance

View 5 Replies View Related

Select DISTINCT On Multiple Columns Is Not Returning Distinct Rows?

Jul 6, 2007

Hi, I have the following script segment which is failing:

CREATE TABLE #LatLong (Latitude DECIMAL, Longitude DECIMAL, PRIMARY KEY (Latitude, Longitude))

INSERT INTO #LatLong SELECT DISTINCT Latitude, Longitude FROM RGCcache



When I run it I get the following error: "Violation of PRIMARY KEY constraint 'PK__#LatLong__________7CE3D9D4'. Cannot insert duplicate key in object 'dbo.#LatLong'."



Im not sure how this is failing as when I try creating another table with 2 decimal columns and repeated values, select distinct only returns distinct pairs of values.

The failure may be related to the fact that RGCcache has about 10 million rows, but I can't see why.

Any ideas?

View 2 Replies View Related

Correlated Subquery With Distinct Record

Jul 20, 2005

record_id Status Due_date549In Progress2004-06-02 00:00:00.000549Not Started2004-06-07 00:00:00.000549Not Started2004-06-08 00:00:00.000549Waiting 2004-05-31 00:00:00.000549Waiting 2004-06-04 00:00:00.000550Completed2004-05-05 00:00:00.000551Completed2004-05-06 00:00:00.000551Completed2004-05-07 00:00:00.000551Completed2004-05-10 00:00:00.000551Not Started1900-01-01 00:00:00.000552Not Started1900-01-01 00:00:00.000Hi I have this table with 3 columns.. What I want isDistinct(record_id),max(due_date) and Status.. I tried thisselect distinct(record_id),status,(due_date) from table1 where(due_date) in(select max(due_date) from table1 as A where a.record_id=record_idand a.due_date is not null group by a.record_id,status)So the result that I want isRecord Status Max(due_date)549Not Started2004-06-09 00:00:00.000550Completed2004-05-05 00:00:00.000551Completed2004-05-10 00:00:00.000Any help is appreciated..ThanksAJ

View 3 Replies View Related

Distinct Record Equal To 2 Values From Same Column

Dec 6, 2013

Distinct name that match both subjects (math, science) from classname in level 2 only. Not sure where to even start. Example table below:

name subject level
bob math 2
hank math 1
joe science 2
bob science 2
joe math 2
ben science 2
carl science 1

View 2 Replies View Related

Select Distinct Record Only If Certain Column Not Null

Apr 5, 2007

Been trying to come up with a query to filter-down my sample set intodistinct records. For instance, lets say column1 is a sample set,column2 is the parameter, and column3 is a name and column4 is a type(lets also say there is a fifth column (id) that is an id). What Ineed is one record per type per sample only if type is given, if not,then return that record as well.I've used a subquery to get as close to the desired query is aspossible:select * from table1where id in (select min(id) from table1where column1="A"group by column1, column2)Here's an example of all data for sample "A":1 2 3 4----------A 1 X PA 1 Y PA 1 Z PA 2 WA 3 WA 4 T PA 5 U PA 6 V PA 7 TA 7 UA 7 VI want output :1 2 3-------A 1 X PA 2 WA 3 WA 4 T PA 5 U PA 6 V PA 7 TA 7 UA 7 VExcept the above query will exclude the last two records becausecolumn3 is not 'grouped by'.Basically I need to reduce any 'range' of records per sample (columna) where column4 is not null (ie = 'P'), to only one record andkeeping all others. Thanks in advance:-B

View 6 Replies View Related

DISTINCT To ShortDateString, Not DISTINCT To The DateTime; How?

May 8, 2006

Hello,
I have written a small asp.net application, which keeps record of the proposals coming from the branch offices of a bank in a tableCREATEd as a TABLE Proposals ( ID smallint identity(7,1), BranchID char(5), Proposal_Date datetime )
This app also calculates the total number of proposals coming from a specific branch in a given date bySELECTing COUNT(BranchID) FROM Proposals WHERE BranchID=@prmBranchID AND Proposal_Date=@prmDateand prints them in a table (my target table).
This target table has as many rows as the result of  the "SELECT COUNT( DISTINCT Proposal_Date ) FROM Proposals"and excluding the first column which displays those DISTINCT Proposal_Dates, it also has as many columns as the result of the"SELECT DISTINCT BranchID FROM Proposals". This target table converts the DateTime values ToShortDateString so that we are able to see comfortably which branch office has sent how many proposals in a given day.
So far so good, and everything works fine except one thing:
Certain DateTime values in the Proposals table which are of the same day but of different hours (for ex: 11.11.2005 08:30:45 and11.11.2005 10:45:30) cause some trouble in the target table,  where "SELECT COUNT( DISTINCT Proposal_Date ) FROM Proposals" is executed, because (as you might already guess) it displays two identical dates in ShortDateString form, and this doesn't make much sense (i.e. it causes redundant rows)
What I need to do is to get a result like (in a neat fashion :)
"SELECT COUNT( DISTINCT Proposal_Date ) <<DISTINCT ONLY IN THE DAYS AND NOT IN HOURS OR MINUTES OR SECONDS>> FROM Proposals"
So, how to do it in a suitable way?
Thanks in advance.

View 4 Replies View Related

Max With Distinct Two Columns And Corresponding Third Field

Apr 30, 2014

i need to write a query and can't get it to work no matter how it try. Here's what i need:

T1
-------
a1
a2
datetime
a4
a5
.....

i need distinct max between a1&a2 which i can get no problem but i cant get that unique datetime that correspond to a1&a2 in 1 query because this is will a subquery in a big query. Creating another temp table etc is not an option for me.for every specific a1 there is many entries of a2 + timedate etc.

Code:
T1
-----------------------------
a1 a2 timedate

1 1 2014-04-31 10:59:38.000 ......
1 2 2014-04-31 10:59:39.000 .......
1 3 2014-04-31 10:59:39.500 .......
2 1 timedate .......
2 2 timedate .......etc

select distinct t1.a1
,max (t1.a2)
from t1

View 5 Replies View Related

SQL Distinct Value And Order By Some Field......

Jan 4, 2006

Dear all,In SQL Server 2000 , how to get distinct records sort by onefield .ExampleSELECT DISTINCT A FROM tblTEST ORBER BY BHere, In TableField 'A' contain more than one same data...Field 'B' contain all are different Data......I want distince in Field 'A' and order by Field 'B'..... how to getit.........regardskrishnan

View 2 Replies View Related

HOW TO USE DISTINCT IN SELECT STATEMENT TO FILTER OUT DUPLICATED RECORD??

Jan 5, 2001

I HAVE A SELECT STATEMENT WITH TEACHERS AND STUDENTS AND SOMETHING ELSE TOO.
FOR EACH TEACHER I ONLY NEED ONE(FIRST ONE) STUDENT.
HOW THE STATEMENT SHOULD BE?

SELECT DISTINCT .... TID, SID, SOMETHING ???????

View 3 Replies View Related

Select Distinct On Field With Values Seperated By

Apr 5, 2006

I have a db that contains a column named DSCODES. Values in DSCODES are seperated by a comma.

If I run the following command.

select distinct(DSCODES) from DB

The following is returned.

S100,S102,S103
S100,S103,S105

What I would like returned is the following

S100
S102
S103
S105

Is this possible?

Thank you in advance

Graham

View 2 Replies View Related

SELECT DISTINCT To Return Only The YEARS In A Date Field?

Mar 22, 2006

I have a table in my MS SQL 2000 database called News which has a field caled NewsDate. This is a standard Date field which stores the info in this format: 3/1/2001.

I want to create a query that returns one row for each year that there is a story.


For example, if I had this data...
3/1/2001, 6/27/2003. 9/17/2003, 1/1/2006, 4/5/2006

the query would return this result:

2001
2003
2006


This is the query I've started with:


SELECT DISTINCT NewsDate FROM News ORDER BY NewsDate DESC


What modifier can I apply to the NewsDate field to extract JUST the year from the table? If this were ASP I would try something like Year(Date), but, of course, I can't do that here.

Is this even possible? I've been looking up date functions, but haven't found anything that will work in a select statement. ANY and ALL advice will be greatly appreciated.

View 1 Replies View Related

Looking To Collect Distinct Date Part Out Of Datetime Field

Mar 11, 2006

from this, circdate being a datetime field:SQLQuery = "select distinct circdate from circdata order by circdate"I need the distinct date portion excluding the time part.this has come about when I discoveredI am inserting and updating some datetime values with the same value,but for some reason, the values are always off by a few seconds. I seta variable called SetNow assigned to NOW and then set the datetimefields to this SetNow variable. Then when I collect the distinct datetime I am assuming they will have the same values recorded incircdate, but no, they are off by several seconds. Makes no sense to meat all. I tried renaming the variable several times but it makes nodifference at all.any help appreciated, thanks.

View 5 Replies View Related

Transact SQL :: How To Get All Distinct Values From 10 Different Tables That Exist In The Field

Aug 19, 2015

I need to get all distinct values from 10 different tables that exist in the field [favoritesport]  And each table holds close to 50K records so I am looking at 500,000 records to get distinct values for.  Would the fastest, less intrusive way of achieving this be to just create a UNION ALL so run 

Select Distinct([favoritesport]) from table1
Union
Select Distinct([favoritesport]) from table2
Union
Select Distinct([favoritesport]) from table3
etc etc etc

View 2 Replies View Related

DISTINCT QUERY PLEASE HELP

Oct 23, 2005

I do an distinct query like this:query = "SELECT DISTINCT name, total = COUNT(*) from products where name LIKE '%" & searchString & "%' GROUP BY name"The query works fine but I need to select one more field called "info" so I just tried this:query = "SELECT DISTINCT name, info, total  = COUNT(*) from products where name LIKE '%" & searchString & "%' GROUP BY name"but then I get the error message:"Column 'products.info' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"I want do group just by "name" and not "info"How can I select this "info" field to?? somebody know??

View 2 Replies View Related

TOP Query With DISTINCT

May 22, 2000

Have a query that uses TOP 10; but I'm not receiving unique results and haven't been able to figure out using DISTINCT with TOP. Is it possible to use TOP with DISTINCT?

Thanks for any help/suggestions.

View 1 Replies View Related

Distinct Query Help

Sep 10, 2007

i'm in need of help woth this query, i've edited my post.

just click the link below

http://www.geocities.com/gateofgalesph/qry/index.html

thank you :)

View 1 Replies View Related

Distinct Row Query

Jun 18, 1999

I need help with a query on a single table.

The table in name, date, ss# and I need to get unique rows, but there can me many ss# to each date. I need to get the max date for each unique ss#.

Select distinct name, date, ss#

returns all rows, because dates are different, but I need to have the results contain all three columns of information.

Thanks for the help,

-Ken

View 1 Replies View Related

Distinct Query Help

Jan 8, 2005

Hi,

how can i run a distinct query on ONE column from one table that will show all columns.

SELECT DISTINCT *
FROM invInactive
WHERE (status = '13')

tagnum, status, inactivedate
----------------------------
1033, 13, today
1033, 13, yesterday
1095, 13, today
1205, 13, yesterday

basically, i just want to show this:
tagnum, status, inactivedate
----------------------------
1033, 13, today
1033, 13, yesterday

thanks for your help.
gonad.

View 1 Replies View Related

Distinct To Query

Jun 12, 2005

Code:

CREATE PROCEDURE [dbo].[CastCompare]
@ID int,
@TopRecords int,
@Type int

AS

DECLARE @SQLSelect nVarchar(1000)

SET @SQLSelect = 'SELECT TOP ' + CAST(@TopRecords AS Varchar(10)) + ' * FROM TblCastList,TblCast where TblCastList.ProductResellerID=TblCast.ResellerID and TblCastList.ProductID=' + CAST(@ID AS Varchar(10)) + ' and TblCastList.Type=' + CAST(@Type AS Varchar(10)) + ' order by TblCast.[name] asc '

Exec sp_executesql @SQLSelect
GO



how Can I add distinct command to query ?
I tried something but none of them is work.

I want to add
distinct TblCastList.[ProductResellerID]

View 3 Replies View Related

A Distinct Query

Aug 2, 2004

I have 2 tables as following :

tbl_Articles
3ArticleIDint
0AuthorIDint
0ArticleTitle
0ArticleText
0ArticleDate

tbl_Authors
3AuthorID
0AuthorFullName
0AuthorEmail
0AuthorDescription
0AuthorImage

I want to write a query to see the Authors and their last articles with no distinct values.
Like AuthorImage - AuthorFullName - ArticleTitle - ArticleDate

If anyone knows the solution i will be glad .
Thanks from now on

View 2 Replies View Related

Distinct Query

Nov 7, 2005

When i run this query,
select distinct(firstname + ' ' + lastname), firstname, lastname, department
from tbltest

it brings out 149 records

but when i run it with the extension field

select distinct(firstname + ' ' + lastname), firstname, lastname, department, extension
from tbltest

Is there like a limit to the distinct query on the number of columns returned ?

View 1 Replies View Related

Query Help, Distinct Row

Apr 21, 2008

I have the following query:

SELECT DISTINCT PC.ContentID, PC.GeoUnitID, PC.ContactID, CT.ID, CT.PageTitle, C.FirstName, C.LastName, C.MainPhoneNO, C.EmailAddress
FROM ProductContacts PC INNER JOIN Content CT ON PC.ContentID = CT.ID INNER JOIN Contacts C ON PC.ContactID = C.ContactID
WHERE PC.GeoUnitID = @GeoUnitID
ORDER BY CT.PageTitle ASC

The problem I'm having is two rows have the same ContentID with a different ContactID. I want to only return a single row for each ContentID.

Is there a way around this?

View 3 Replies View Related

Help With Distinct Query

Aug 15, 2007

Here's my query:

SELECT NotYetPublished, Available, Catalogx, pubdate, pubdate_full, NYP, Fulfillment, Title from finaldata where available <> 'Out-of-Print' or (totalnew <>0 and totalused <>0 and totalcollectible<>0) order by NYP desc, pubdate_full desc, Fulfillment desc, Title

I only want to return records that do not have the same Catalogx. I can't use distinct since some of the other data is different.

How can I accomplish this? Thanks in advance.

View 4 Replies View Related

Help With A Distinct Query

Nov 12, 2007

Hello everybody

I'm kind of newbie and I like to know if you can solve me a question,

The fact is I'm trying to gather some information and I don't know how. What I want to do is retrieve the values of five columns, the first one is the primary key, but the others must be unique (all together)

PK Value1 Value2 Value3 Value4
1 3 5 6 3
2 3 5 7 2
3 4 3 1 4
4 3 5 6 3 <- =PK1


I've tried with:

SELECT MesuraA, MesuraB, MesuraC, MesuraD
FROM (SELECT DISTINCT MesuraA, MesuraB, MesuraC, MesuraD
FROM barres_Ciampalini) AS derivedtbl_1

But I don't know how to retrieve the Id.

How Can I do that?

Thanks for read

View 8 Replies View Related

DISTINCT QUERY

Jul 20, 2005

This is probably easy but I can't work it out. I have this statementSELECT DISTINCT TOP 100 PERCENT dbo.CIF_PlaceReference.NameFROM dbo.CIF_Departures INNER JOINdbo.CIF_PlaceReference ON dbo.CIF_Departures.EndPoint= dbo.CIF_PlaceReference.PlaceIDORDER BY dbo.CIF_PlaceReference.NameThis results in a column of placenames which is OK. There are also multiple'time of day' values against each placename however I only want to returnthe one nearest to the current time. If I do this...SELECT DISTINCT TOP 100 PERCENTdbo.CIF_PlaceReference.Name,dbo.CIF_Departures.Sta rtTimeFROM dbo.CIF_Departures INNER JOINdbo.CIF_PlaceReference ON dbo.CIF_Departures.EndPoint= dbo.CIF_PlaceReference.PlaceIDORDER BY dbo.CIF_PlaceReference.Name.... I get multiple place names.Any ideas?

View 8 Replies View Related

Getting Distinct Entries In Query.

Mar 18, 2008

Hello,
I have a reference table.  This table has an effective date and end date, and I need to get a single set of values at a point in time.  Suppose the following hotel rating values are the values that I want to pull out of the table:
1  Star2 Star
3 Star
4 Star
5 Star
This value has other information associated with it (benchmarks and such) and so it's possible that one of the 2 star entries gets end-dated, and then a new 2 Star entry gets created with an effective date and no end date.
How can I query so that I only get one 2 Star entry at any point, and get the point in time where the date is between the effective and end date, but only pull back a single set of entries, one distinct rating value.  So, suppose the first entry is end-dated 7/1, if I look at old data, I want to see the old benchmarks and so I want the previous entry end-dated 7/1; otherwise, I want to see the new end-date, with the new 2 star entry with no end date.
How do I do that?  Make sense?

View 1 Replies View Related

How To Distinct Data By Using MS SQL Query

Apr 29, 2008

Select A.SNO , A.Name , B.Picfrom Student A Left Join Picture BWhere A.SNo = B.PNoNo     SNo            Name                Pic1      000            Andy                /Doc/andy.jpg2      001            Andy                /Doc/andy2.jpg3      002            VIVI                /Doc/vivi.jpg4      003            VIVI                /Doc/Vivi2.jpg The same person will only show 1 pic Pathlike this resultNo     SNo            Name                Pic1      000            Andy                /Doc/andy.jpg3      002            VIVI                /Doc/vivi.jpgcan you please help? I trid use Group By but it not works..thank you

View 10 Replies View Related

Simple Distinct Query (?)

Aug 19, 2005

I have what I thought should be a simple query that's not quite as simple as I thought. Maybe I haven't had enough coffee yet.

Here's the scenario,

Data table looks like this :


COLUMN A is Primary Key
COLUMN B is UserID
COLUMN C is (for example purposes) an int field

A B C
1 1 SOME VALUE
2 1 SOME VALUE
3 1 SOME VALUE
4 2 SOME VALUE
5 2 SOME VALUE
6 2 SOME VALUE
7 3 SOME VALUE
8 3 SOME VALUE
9 3 SOME VALUE


The query that I'm looking for would return all 3 columns but only the first row for each distinct (unique) UserID (Column B)

Hope that all makes sense! ;)

View 4 Replies View Related

Distinct Count Query

Dec 11, 2007

I have a table with following fields
tdate
custcode
prodcode


table is filled with full year data and i want following result

I want count of distinct custcode in every past three months.

for example
Result like this

month tjan tfeb tmar tapr tmay ..... tdec

prod1
prod2
.
.
prod5

And data under tmar should be count of distinct custcode of (jan,feb and mar) for corresponding prod code is required.
Under tapr, count of distinct custcode of (feb,mar and apr) for corresponding prod code is required.

Can any1 help me please.

I am using MS SQL 2005 and above table is a big table (approx 10 million records)

Sham

View 13 Replies View Related

Query For Distinct Dates

Sep 4, 2014

I have a need to only find distinct dates in which a worker worked in the factory using TSQL

Code:
RowNumber workerstartDate workerenddate
1 2012-08-08 2012-10-10
2 2012-08-10 2012-08-31
3 2012-09-05 2012-09-15
4 2012-10-15 2012-12-19
5 2013-01-02 2013-03-14
62013-03-15 2013-05-23

Basically, I am looking for the above to look like this

Code:
rownumberworkerstartDate workerenddate
12012-08-08 2012-10-10
42012-10-15 2012-12-19
52013-01-02 2013-03-14
62013-03-15 2013-05-23

View 2 Replies View Related

Selecting A Distinct Row Query

May 13, 2004

I am trying to append data from a source table to a destination table, the only difference between the tables is that a primary key has been established on the destination table. Problem is, the source table has a handful of duplicate values in the column that corresponds to primary on destination table; so when I run the query I get a primary key conflict. What I'd like to do is select distinct values from the source table to avoid the conflict, but am having trouble getting it to run. Here is the statement-

INSERT INTO cust_master
SELECT DISTINCT cust_master_temp.*
FROM cust_mast_temp LEFT OUTER JOIN
cust_master ON cust_master.temp.CUST_NUMBER = cust_master.CUST_NUMBER

Doesn't seem to be understanding "Distinct"

Any Ideas?

View 2 Replies View Related

Distinct Custnumbers In Query

May 19, 2008

Here's my query:

Select portfolio, custnumber from table

some custnumbers are the same. However I only want the query to include one portfolio per custnumber, ideally the first portfolio.

How would I accomplish this?

Many thanks!

View 7 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved