Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Two Different WHERE Conditions for Two Columns

Tags:

sql-server

How can I return two columns that each use different WHERE critia? Obviously, this won't work:

SELECT Name, COUNT(Column1) AS Total, COUNT(Column1) AS YearToDate
FROM Table1
WHERE Occurred_Date BETWEEN '2010-06-01' AND '2010-06-30' --Total
WHERE Occurred_Date BETWEEN '2010-01-01' AND '2010-06-30' --YearToDate

This is the output I'm looking for:

Name  | Total | YTD  
-------------------
Item1 | 2     | 3
Item2 | 4     | 8
like image 782
Matt Hanson Avatar asked Jun 21 '10 18:06

Matt Hanson


People also ask

Can we use two WHERE condition in SQL?

Example - Two Conditions in the WHERE Clause (AND Condition)You can use the AND condition in the WHERE clause to specify more than 1 condition that must be met for the record to be selected.

How do I combine two conditions in SQL?

Syntax. SELECT column1, column2, columnN FROM table_name WHERE [condition1] AND [condition2]... AND [conditionN]; You can combine N number of conditions using the AND operator.

Can WHERE clause have 2 conditions?

You can specify multiple conditions in a single WHERE clause to, say, retrieve rows based on the values in multiple columns. You can use the AND and OR operators to combine two or more conditions into a compound condition. AND, OR, and a third operator, NOT, are logical operators.

Can we use two columns in WHERE clause in SQL?

Answer. Yes, within a WHERE clause you can compare the values of two columns.


1 Answers

You can also use

SELECT m.count, ytd.count FROM 
   (SELECT COUNT( id ) count FROM table WHERE date BETWEEN '2010-06-01' AND '2010-06-30') m, 
   (SELECT COUNT( id ) count FROM table WHERE date BETWEEN '2010-01-01' AND '2010-06-30') ytd 
like image 193
nico Avatar answered Sep 28 '22 18:09

nico