0

I am new to SQL and I am having trouble constructing a SELECT statement.

What I would like to do is select distinct parts that have a location of A1 if it exists. If a part has no locations of A1 I would like to select distinct material with no condition of location.

Is there a way to make this select statement 1 query or do I need to break it up in selecting the distinct condition true values and selecting the distinct condition false values?

Sample data:

+------+------+----------+
| PART | TYPE | Location |
+------+------+----------+
| A    |    1 | A1       |
| A    |    2 | A1       |
| A    |    1 | A2       |
| A    |    2 | A2       |
| B    |    1 | A2       |
| B    |    1 | A3       |
+------+------+----------+
1
  • 3
    Richard, I'd suggest you edit your question to add what the desired output should be, and how you get from the sample data to this output Commented Apr 18, 2016 at 13:13

3 Answers 3

2

How about a little 2 in 1 using CTE?

;with cte as (
    select top 1 loc = 1
    from parts 
    where Location = 'A1'
)
select distinct Part --, Type, Location
from parts left join cte on 1=1
where loc is null or Location = 'A1';
2
select distinct t1.part 
from table t1 
where t1.Location = 'A1' 
      or not exists (select 1 from table where Location = 'A1')
2

In simple words, it could be put as:

If the table has the A1 location, give me every distinct part that is the A1 location. Otherwise give me every distinct part regardless of location.

Based on that, the query could be built like this:

WITH cte AS
  (
    SELECT
      *,
      TableHasA1 = COUNT(DISTINCT CASE Location WHEN 'A1' THEN 1 END) OVER (),
      RowIsA1    = CASE Location WHEN 'A1' THEN 1 ELSE 0 END
    FROM
      dbo.atable
  )
SELECT DISTINCT
  PART
FROM
  cte
WHERE
  TableHasA1 = RowIsA1
;
  • The TableHasA1 value will be the same for all the rows. It will be either 1 or 0 depending on whether A1 rows are present in the table or not present. The RowIsA1 value will be 1 for A1 rows and 0 for non-A1 rows.

  • If TableHasA1 is 1, then there will definitely be some rows for which RowIsA1 is 1 as well – and TableHasA1 = RowIsA1 will give only those rows, thus satisfying the first half of the problem description.

  • If TableHasA1 is 0, then RowIsA1 will be 0 for all the rows – and so the same condition will this time match all the rows, which fulfils the other half of the problem description.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.