Solved

SQL nested SELECT statement for column

Posted on 2010-11-23
3
324 Views
Last Modified: 2012-05-10
I am trying to select a column inside of a SELECT statement that pulls vlaues out where a different column equals a value.  This is an example of what I want to do but it is not correct:

SELECT column1, column2, (SELECT column 3 WHERE column6 <= 12 AND column10 >= 1 AS YearlySum), column 3, column4, column 5 FROM table1

As you can see I would like to select all of the columns from the table, but also select some of the columns based on certain conditions.  Any hlep is greatly appreciated.
0
Comment
Question by:zintech
3 Comments
 
LVL 142

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 500 total points
ID: 34196828
you cannot optionally select a column.
you could return a NULL value optionally ...
SELECT column1, column2

, CASE WHEN column6 <= 12 AND column10 >= 1 THEN column3 ELSE NULL END AS YearlySum

, column 3, column4, column 5 

FROM table1

Open in new window

0
 
LVL 3

Expert Comment

by:ppango
ID: 34196846
To accomplish this you need to use the CASE clause

But my first question will be this one, what if the condition you specified is not met? lets say Column 6 is grater then 12 and column 10 less than 1?

Thanks

0
 
LVL 5

Expert Comment

by:logideepak
ID: 34196908
you can use a case statement

SELECT column1, column2, case when  column6 <= 12 AND column10 >= 1 then column3 else null end  AS YearlySum, column 3, column4, column 5 FROM table1
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

Composite queries are used to retrieve the results from joining multiple queries after applying any filters. UNION, INTERSECT, MINUS, and UNION ALL are some of the operators used to get certain desired results.‚Äč
This article describes how to use the timestamp of existing data in a database to allow Tableau to calculate the prior work day instead of relying on case statements or if statements to calculate the days of the week.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now