473,706 Members | 2,033 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

select distinct record only if certain column not null

Been trying to come up with a query to filter-down my sample set into
distinct 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 I
need 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 as
possible:

select * from table1
where id in (select min(id) from table1
where column1="A"
group by column1, column2)

Here's an example of all data for sample "A":

1 2 3 4
----------
A 1 X P
A 1 Y P
A 1 Z P
A 2 W
A 3 W
A 4 T P
A 5 U P
A 6 V P
A 7 T
A 7 U
A 7 V

I want output :

1 2 3
-------
A 1 X P
A 2 W
A 3 W
A 4 T P
A 5 U P
A 6 V P
A 7 T
A 7 U
A 7 V

Except the above query will exclude the last two records because
column3 is not 'grouped by'.

Basically I need to reduce any 'range' of records per sample (column
a) where column4 is not null (ie = 'P'), to only one record and
keeping all others. Thanks in advance:

-B

Apr 5 '07 #1
6 20871
(pl******@gmail .com) writes:
Been trying to come up with a query to filter-down my sample set into
distinct 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 I
need is one record per type per sample only if type is given, if not,
then return that record as well.
...
I want output :

1 2 3
-------
A 1 X P
A 2 W
A 3 W
A 4 T P
A 5 U P
A 6 V P
A 7 T
A 7 U
A 7 V
Since you did not provide CREATE TABLE and INSERT statements with the
sample data, this is untested:

SELECT col1, col2, col3, col4
FROM (SELECT col1, col2, col3, col4,
rn = row_number() OVER(PARTITION BY col1, col2
ORDER BY col3)
FROM tbl) AS d
WHERE rn = CASE WHEN col4 IS NOT NULL THEN 1 ELSE rn END
This solution requires SQL 2005. Tip: always say which version of
SQL Server you are using.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Apr 5 '07 #2
pl******@gmail. com wrote:
Been trying to come up with a query to filter-down my sample set into
distinct 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 I
need 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 as
possible:

select * from table1
where id in (select min(id) from table1
where column1="A"
group by column1, column2)

Here's an example of all data for sample "A":

1 2 3 4
----------
A 1 X P
A 1 Y P
A 1 Z P
A 2 W
A 3 W
A 4 T P
A 5 U P
A 6 V P
A 7 T
A 7 U
A 7 V

I want output :

1 2 3
-------
A 1 X P
A 2 W
A 3 W
A 4 T P
A 5 U P
A 6 V P
A 7 T
A 7 U
A 7 V

Except the above query will exclude the last two records because
column3 is not 'grouped by'.

Basically I need to reduce any 'range' of records per sample (column
a) where column4 is not null (ie = 'P'), to only one record and
keeping all others. Thanks in advance:
What about this?

select column1, column2, column3, column4
from table1
where id in (
select min(id)
from table1
group by column1, column2
)
and column4 is not null
union
select column1, column2, column3, column4
from table1
where column4 is null

What would you want to do with the following data?

1 2 3 4 id
----------
A 8 X P 12
A 8 Y Q 13
A 9 X P 14
A 9 Y 15 <- column4 is null
Apr 6 '07 #3
On Apr 5, 4:55 pm, Erland Sommarskog <esq...@sommars kog.sewrote:
(plast...@gmail .com) writes:
Been trying to come up with a query to filter-down my sample set into
distinct 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 I
need is one record per type per sample only if type is given, if not,
then return that record as well.
...
I want output :
1 2 3
-------
A 1 X P
A 2 W
A 3 W
A 4 T P
A 5 U P
A 6 V P
A 7 T
A 7 U
A 7 V

Since you did not provide CREATE TABLE and INSERT statements with the
sample data, this is untested:

SELECT col1, col2, col3, col4
FROM (SELECT col1, col2, col3, col4,
rn = row_number() OVER(PARTITION BY col1, col2
ORDER BY col3)
FROM tbl) AS d
WHERE rn = CASE WHEN col4 IS NOT NULL THEN 1 ELSE rn END

This solution requires SQL 2005. Tip: always say which version of
SQL Server you are using.

--
Erland Sommarskog, SQL Server MVP, esq...@sommarsk og.se

Books Online for SQL Server 2005 athttp://www.microsoft.c om/technet/prodtechnol/sql/2005/downloads/books...
Books Online for SQL Server 2000 athttp://www.microsoft.c om/sql/prodinfo/previousversion s/books.mspx- Hide quoted text -

- Show quoted text -
Thanks for the response, and sorry for the lack of info: SQL ver 7.0

-b

Apr 9 '07 #4
On Apr 5, 10:04 pm, Ed Murphy <emurph...@soca l.rr.comwrote:
plast...@gmail. com wrote:
Been trying to come up with a query to filter-down my sample set into
distinct 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 I
need 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 as
possible:
select * from table1
where id in (select min(id) from table1
where column1="A"
group by column1, column2)
Here's an example of all data for sample "A":
1 2 3 4
----------
A 1 X P
A 1 Y P
A 1 Z P
A 2 W
A 3 W
A 4 T P
A 5 U P
A 6 V P
A 7 T
A 7 U
A 7 V
I want output :
1 2 3
-------
A 1 X P
A 2 W
A 3 W
A 4 T P
A 5 U P
A 6 V P
A 7 T
A 7 U
A 7 V
Except the above query will exclude the last two records because
column3 is not 'grouped by'.
Basically I need to reduce any 'range' of records per sample (column
a) where column4 is not null (ie = 'P'), to only one record and
keeping all others. Thanks in advance:

What about this?

select column1, column2, column3, column4
from table1
where id in (
select min(id)
from table1
group by column1, column2
)
and column4 is not null
union
select column1, column2, column3, column4
from table1
where column4 is null

What would you want to do with the following data?

1 2 3 4 id
----------
A 8 X P 12
A 8 Y Q 13
A 9 X P 14
A 9 Y 15 <- column4 is null- Hide quoted text -

- Show quoted text -
Thanks Ed. Although i'm getting syntax issues with the UNION portion
of you query. Perhaps that's a version issue as well (i'm using SQL
server 7.0).

Apr 9 '07 #5
(pl******@gmail .com) writes:
Thanks Ed. Although i'm getting syntax issues with the UNION portion
of you query. Perhaps that's a version issue as well (i'm using SQL
server 7.0).
A common recommendation is that you post:

o CREATE TABLE statements for your tables.
o INSERT statements with sample data.
o The desired output given the sample.

This makes it easy to copy and paste to develop a tested solution. Without
that, you get more or less guessworks.

Ed's query should be OK in SQL 7, but 1) I don't know how you adapted it
to your problem 2) what error message you got.


--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Apr 9 '07 #6
On Apr 9, 4:59 pm, Erland Sommarskog <esq...@sommars kog.sewrote:
(plast...@gmail .com) writes:
Thanks Ed. Although i'm getting syntax issues with the UNION portion
of you query. Perhaps that's a version issue as well (i'm using SQL
server 7.0).

A common recommendation is that you post:

o CREATE TABLE statements for your tables.
o INSERT statements with sample data.
o The desired output given the sample.

This makes it easy to copy and paste to develop a tested solution. Without
that, you get more or less guessworks.

Ed's query should be OK in SQL 7, but 1) I don't know how you adapted it
to your problem 2) what error message you got.

--
Erland Sommarskog, SQL Server MVP, esq...@sommarsk og.se

Books Online for SQL Server 2005 athttp://www.microsoft.c om/technet/prodtechnol/sql/2005/downloads/books...
Books Online for SQL Server 2000 athttp://www.microsoft.c om/sql/prodinfo/previousversion s/books.mspx
You're right Erland, Ed's UNION query did the trick after a slight
amount of tweeking. I'll definitely use your advice as well when
posting to the groups. Thanks to you both for your time!

-B

Apr 10 '07 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2413
by: skidvd | last post by:
Hello: I have just recently converted to using the InnoDB table type so that I can enforce FOREIGN key constraints. I have been using MyISAM tables (accessed via JDBC) successfully for some time. However, I have just come across a problem with the new configuration that boggles my mind.... First some configuration data:
0
1283
by: Rob Knowles | last post by:
I have created a script that runs once a week and copies data from one table (phpbb_users is the actual table name) in a database called users I have a table called users. There are two tables in this database. The table names are: phpbb_users phpbb_users_backup
5
1808
by: Reestit Mutton | last post by:
Hi, I'm currently learning the ropes with CSS, PHP, MYSQL, Javascript etc... by redesigning my website as a database driven site. Okay, so I'm skilled at perl, data manipulation and data analysis and I've done a fair bit of (non CSS) HTML in the past and know what a relational database is. However, I'm having problems trying to formulate a particular MYSQL query (maybe I just don't know the lingo or maybe I've designed my data...
18
3054
by: mathilda | last post by:
My boss has been adamant that SELECT DISTINCT is a faster query than SELECT all other factors being equal. I disagree. We are linking an Access front end to a SQL Server back end and normally are only returning one record. She states that with disctinct the query stops as soon as it finds a matching record. Both of us are relative novices in database theory (obviously). Can someone help settle this?
2
4847
by: Frank van Vugt | last post by:
Hi, Not exactly a showstopper, but I noticed this behaviour: db=# create table f1 (id int, value int); CREATE TABLE db=# insert into f1 select 1 as id, null; INSERT 25456306 1
6
4845
by: jjturon | last post by:
Can anyone help me?? I am trying to pass a Select Query variable to a table using Dlookup and return the value to same select query but to another field. Ex. SalesManID SalesManName AT Alan Time
22
12479
by: MP | last post by:
vb6,ado,mdb,win2k i pass the sql string to the .Execute method on the open connection to Table_Name(const) db table fwiw (the connection opened via class wrapper:) msConnString = "Data Source=" & msDbFilename moConn.Properties("Persist Security Info") = False moConn.ConnectionString = msConnString moConn.CursorLocation = adUseClient moConn.Mode = adModeReadWrite' or using default...same result
2
1607
Spazasaurus
by: Spazasaurus | last post by:
I am having trouble. I am not sure if it is not possible or not, but don't know any alternatives. I am converting my site from PHP and MYSQL to ASP.NET and MSSQL. In my current site. I did a query and then did another query on each record while looping through those results to get what I am trying to do in one query now. I would simply do that same thing but I am not sure how while using Visual Studio and I know that it was bad code, so...
4
10677
tjc0ol
by: tjc0ol | last post by:
Hi guys, I'm a newbie in php and I got error in my index.php which is: 1054 - Unknown column 'p.products_id' in 'on clause' select p.products_image, pd.products_name, p.products_id, p.manufacturers_id, p.products_price, p.products_tax_class_id, IF(s.status, s.specials_new_products_price, NULL) as specials_new_products_price, IF(s.status, s.specials_new_products_price, p.products_price) as final_price from products_description pd,...
0
8779
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
8695
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9282
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9048
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
5937
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4445
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4708
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3142
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2499
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.