How to get DATE from DATETIME Column in SQL?
SqlSql ServerDateDatetimeSql Problem Overview
I have 3 columns in Table TransactionMaster in sql server
-
transaction_amount
-
Card_No
-
transaction_date--
datetime
datatype
So, I want to fetch SUM of transaction_amount where Card_No=' 123'
and transaction_date= todays date
.<----- excluding time IN SQL
Sql Solutions
Solution 1 - Sql
Simply cast your timestamp AS DATE
, like this:
SELECT CAST(tstamp AS DATE)
In other words, your statement would look like this:
SELECT SUM(transaction_amount)
FROM mytable
WHERE Card_No='123'
AND CAST(transaction_date AS DATE) = target_date
What is nice about CAST
is that it works exactly the same on most SQL engines (SQL Server, PostgreSQL, MySQL), and is much easier to remember how to use it.
Methods using CONVERT()
or TO_DATE()
are specific to each SQL engine and make your code non-portable.
Solution 2 - Sql
You can use
select *
from transaction
where (Card_No='123') and (transaction_date = convert(varchar(10),getdate(),101))
Solution 3 - Sql
use the following
select sum(transaction_amount) from TransactionMaste
where Card_No = '123' and transaction_date = CONVERT(VARCHAR(10),GETDATE(),111)
or the following
select sum(transaction_amount) from TransactionMaste
where Card_No = '123' and transaction_date = CONVERT(VARCHAR(10), GETDATE(), 120)
Solution 4 - Sql
Use Getdate()
select sum(transaction_amount) from TransactionMaster
where Card_No=' 123' and transaction_date =convert(varchar(10), getdate(), 102)
Solution 5 - Sql
Try this:
SELECT SUM(transaction_amount) FROM TransactionMaster WHERE Card_No ='123' AND CONVERT(VARCHAR(10),GETDATE(),111)
The GETDATE()
function returns the current date and time from the SQL Server.