SQL Query Question

I have one table, dbo.pricing_levels with the following data:

id (pk)              item          pricing_level_id        price
1000                 XYZ                     1                          $10
1000                 XYZ                     2                             0

I want to query to find every item where we have a positive value in with a pricing_leve_id = 1 and a zero value in a pricing_level=2
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Walter RitzelSenior Software EngineerCommented:
select *
from dbo.pricing_levels here (price > 0 and priicng_level_id = 1) or (price = 0 and pricing_level_id = 2)

Open in new window

Allan ReitanChief Financial OfficerCommented:
  FROM [dbo].[pricing_levels] A CROSS JOIN [dbo].[pricing_levels] B
  WHERE A.pricing_level_id < B.pricing_level_id AND A.[price] > 0;

Another Option without the DISTINCT Clause:

2. SELECT A.[id(pk)]
  FROM [dbo].[pricing_levels] A CROSS JOIN [dbo].[pricing_levels] B
  WHERE A.pricing_level_id < B.pricing_level_id AND A.[price] > 0
  GROUP BY A.[id(pk)]
You can do this with a self join.  
FROM pricing_levels a INNER JOIN pricing_levels b ON a.[id(pk)] - b.[id(pk)]
WHERE a.pricing_level_id = 1 AND b.pricing_level_id = 2 AND a.price > 0 AND b.price = 0

Open in new window

Hope this helps,

Scott PletcherSenior DBACommented:
SELECT pl.id
FROM dbo.pricing_levels pl
GROUP BY pl.id
    MAX(CASE WHEN pl.pricing_level_id = 1 AND pl.price > 0 THEN 1 ELSE 0 END) = 1 AND
    MAX(CASE WHEN pl.pricing_level_id = 2 AND pl.price = 0 THEN 1 ELSE 0 END) = 1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Walter RitzelSenior Software EngineerCommented:
Just as curiosity: care to explain why have you selected this solution and not the others?
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.