Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select value if condition in SQL Server [duplicate]

In a query selection I would like to display the result whether a field satisfies a condition.

Imagine that I have a table called stock. This table has a column that tells me the number of each item in the stock.

What I would like to do is something like this:

SELECT      stock.name, IF (stock.quantity <20, "Buy urgent", "There is enough") FROM stock 

Is there any function in SQL Server to do that?

like image 978
Rumpelstinsk Avatar asked Jul 11 '13 16:07

Rumpelstinsk


People also ask

How do I select duplicate records in SQL?

To select duplicate values, you need to create groups of rows with the same values and then select the groups with counts greater than one. You can achieve that by using GROUP BY and a HAVING clause.

Does select return duplicate rows?

Select Distinct will remove duplicates if the rows are actually duplicated for all columns, but will not eliminate 'duplicates' that have a different value in any column.

Does count (*) include duplicate values?

Yes, when using the COUNT() function on a column in SQL, it will include duplicate values by default. It essentially counts all rows for which there is a value in the column. If you wanted to count only the unique values in a column, then you can utilize the DISTINCT clause within the COUNT() function.


2 Answers

Try Case

SELECT   stock.name,       CASE           WHEN stock.quantity <20 THEN 'Buy urgent'          ELSE 'There is enough'       END FROM stock 
like image 120
Ram Avatar answered Oct 11 '22 04:10

Ram


Have a look at CASE statements
http://msdn.microsoft.com/en-us/library/ms181765.aspx

like image 31
Daniel Hollinrake Avatar answered Oct 11 '22 02:10

Daniel Hollinrake