While using SQL, I've always found myself confused about date formats when solving problems related to dates. In the content below, I need to filter data for January, but the function I wasn't the best way.
SELECT category, sum(sales) 'Total_sales'
from book b inner join book_sales s on b.book_id = s.book_id
WHERE sales_Date BETWEEN '2022-01-01' AND '2022-01-31'
group by 1
order by category
When entering date functions, I achieved the desired results by using 'where between' function from January 1st to January 31st. However, the code looked messy. Was there any way to make it clear and simple?
- Yes there was a way to make it simple
SELECT category, sum(sales) 'Total_sales'
from book b inner join book_sales s on b.book_id = s.book_id
where month(sales_date) = 1
group by 1
order by category
Using 'Where + month(column) = 1'
The expression `WHERE + MONTH(column) = 1` is used to filter records based on the month component of a date column.
Here's a breakdown of how it works:
- `MONTH(column)`: This is a SQL function that extracts the month from the specified date column.
For example, `MONTH('2022-01-15')` would return `1` because it corresponds to January.
- `= 1`: This comparison checks if the month extracted from the column is equal to `1`, indicating January.
'Issue Note' 카테고리의 다른 글
Difference between 'num for num in range' and 'for num in range' (Python) (0) | 2024.04.02 |
---|---|
Difference between list and [] (Python) (0) | 2024.04.02 |
Exclusion of NULL values in b.customer_id column in SQL query [SQL] (0) | 2024.03.22 |
Table name from Subquery [SQL] (0) | 2024.03.21 |
Red highlighted error [SQL] (0) | 2024.03.21 |