In my table, I have some ID's associated with each Date. How do I count the number of ID's associated with a date ? The date column is in datetime, but I want to group by date and not date time.
Expected output -
11/14/2013, 30 counts
11/15/2013, 400 counts
etc
I am using SQL server 2000.
Group by DATEADD(day, DATEDIFF(day, 0, DateTimeCol), 0) which truncates the time to midnight.
SELECT Date = DATEADD(day, DATEDIFF(day, 0, DateTimeCol), 0)
, COUNT = COUNT(*)
FROM dbo.TableName
GROUP BY DATEADD(day, DATEDIFF(day, 0, DateTimeCol), 0)
Related
I have following data in my table,
Table = BillHeader
Sales column = Sales
Date column = CreateDate
Location name = Location
Result needed:
Location
Sum_of_Sale_1
Sum_of_Sale_2
Sum_of_Sale_1 = Sum of Sales up to yesterday for this month.
Sum_of_Sale_2 = Sum of Sales up to same date range as Sum_of_Sale_1 during last month.
For example, if today is 20th of June, Sum_of_Sale_1 = Sum of sales from 1st June to 19th of June
and Sum_of_Sale_2 = Sum of sales from 1st May to 19th of May.
Basically what I need is these two results of different date ranges, which should be selected form the same three columns, should appear next to each other in the result. I want to know how the sales performance was last month's same date range as to this month's date range (up to yesterday for this month).
Thanks!!
EDIT - 1
Here is the actual current working code:
SET #FDM = DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0)
SELECT sum ([LAB_TRN_BillHeader].[AmountToBePaid]) as Total_Sale
,LAB.dbo.[LAB_TRN_BillHeader].[CollectingCenterCode]
,LAB.dbo.[LAB_Comm_MST_CollectingCenter].[Name]
,LAB.dbo.[LAB_Comm_MST_Branch].[BranchName]
FROM Lab.dbo.[LAB_TRN_BillHeader]
INNER JOIN LAB.dbo.[LAB_Comm_MST_CollectingCenter] on LAB.dbo.[LAB_TRN_BillHeader].[CollectingCenterCode] = LAB.dbo.[LAB_Comm_MST_CollectingCenter].[CollectingCenterCode]
INNER JOIN LAB.dbo.[LAB_Comm_MST_Branch] on LAB.dbo.[LAB_TRN_BillHeader].[BranchCode] = LAB.dbo.[LAB_Comm_MST_Branch].[BranchCode]
WHERE Date between #FDM and DATEADD(day,0, CAST(GETDATE() AS date)) and {{select_Laboratory}} and LAB.dbo.[LAB_TRN_BillHeader].[IsVoid] = '0' and LAB.dbo.[LAB_TRN_BillHeader].[CollectingCenterCode] in ('URCR022','MRPMC','KUCC','KOCC','EHECC')
GROUP BY LAB.dbo.[LAB_TRN_BillHeader].[CollectingCenterCode], LAB.dbo.[LAB_Comm_MST_CollectingCenter].[Name], LAB.dbo.[LAB_Comm_MST_Branch].[BranchName]
Current Result:
|Total_Sale|CollectingCenterCode|Name|BranchName|
|xxx |xxx |x |xx |
Required Result:
|Total_Sale|Total_Sale2|CollectingCenterCode|Name|BranchName|
|xxx |xxx |xx |x |xx |
Total_Sale = Sale of current month up to yesterday
Total_Sale2 = Sale of Last month up to current month's yesterday's date.
-- MSSQL Version - 2014
-- <Create_Date> is a time stamp in the table in <Create_Date> column. The date/time is obtained from that timestamp. Each transaction is saved with a respective timestamp at it's time of occurrence.
-- {{select_Laboratory}} is a field filter alias in Metabase (this code was copied from a Metabase dashboard). The actual code is LAB.dbo.[LAB_TRN_BillHeader].[BranchCode] = '001'
Considering a sales CreateDate is likely of type Datetime or Datetime2, a safe approach would be:
DECLARE #yesterday DATE = GETDATE();
DECLARE #lastMonth DATE = DATEADD(MONTH, -1, #yesterday);
DECLARE #firstDayOfThisMonth DATE = DATEADD(DAY, 1 - DAY(#yesterday), #yesterday);
DECLARE #firstDayOfLastMonth DATE = DATEADD(DAY, 1 - DAY(#lastMonth), #lastMonth);
SELECT #yesterday,
#firstDayOfThisMonth,
#lastMonth,
#firstDayOfLastMonth;
SELECT [locationId],
SUM( CASE
WHEN CreateDate >= #firstDayOfThisMonth
AND CreateDate < #yesterday THEN
AmountToBePaid
END
) AS Sum_of_Sale_1,
SUM( CASE
WHEN CreateDate >= #firstDayOfLastMonth
AND CreateDate < #lastMonth THEN
AmountToBePaid
END
) AS Sum_of_Sale_2
FROM BillHeader
GROUP BY [locationId];
EDIT: Note that in dates like March 31,30 previous month's end date could be Feb 28, 29.
You could use conditional aggregation with the following date functions:
DATEADD(Day, 1, EOMONTH(GETDATE(), -1)) gets the first date of the current month, i.e. current month is Jan-2023 it will return '2023-01-01'.
CAST(GETDATE() AS DATE) gets today's date.
DATEADD(Day, 1, EOMONTH(GETDATE(), -2)) gets the first date of the previous month, i.e. current month is Jan-2023 it will return '2022-12-01'.
DATEADD(Month, -1, CAST(GETDATE() AS DATE) gets the date of the day one-month pre today's date.
SELECT Location,
SUM(CASE
WHEN CreateDate >= DATEADD(Day, 1, EOMONTH(GETDATE(), -1)) AND
CreateDate < CAST(GETDATE() AS DATE)
THEN Sales END) Sum_of_Sale_1,
SUM(CASE
WHEN CreateDate >= DATEADD(Day, 1 ,EOMONTH(GETDATE(), -2)) AND
CreateDate < DATEADD(Month, -1, CAST(GETDATE() AS DATE))
THEN Sales END) Sum_of_Sale_2
FROM BillHeader
GROUP BY Location
See demo
There are different ways of doing the calculations and I don't know if this logic will seem more straightforward or as concise. Also you might not be able to use variables. Lastly, you didn't specify which version you're running.
Although you can incorporate this into an existing query that covers a wider range of dates, here is a stand-alone option that should restrict the execution to a narrower range of dates. The case logic, as written, does assume that rows have already been filtered so the only thing left to determine is whether the sale comes from current month or prior month.
select Location,
sum(case when month(CreateDate) <> month(getdate()) then Sales end) as Sales1,
sum(case when month(CreateDate) = month(getdate()) then Sales end) as Sales2
from BillHeader
where
-- go back enough days to guarantee covering last two months
-- this may be able to utilize an index
SalesDate between dateadd(day, -30 - day(getdate()), cast(getdate() as date))
and getdate()
-- now eliminate extra dates that are not relevant
and month(getdate()) - month(CreateDate) in (0, 1, -11) /* year might roll over */
and day(getdate()) > day(CreateDate)
group by Location;
For a YOY comparison over the same calendar month:
select Location,
sum(case when year(CreateDate) <> year(getdate()) then Sales end) as Sales1,
sum(case when year(CreateDate) = year(getdate()) then Sales end) as Sales2
from BillHeader
where
-- go back enough days to guarantee covering last 13 months
-- (or rewind as 396 days via parallel logic from earlier)
SalesDate between
dateadd(year, -1, dateadd(day, 1 - day(getdate()), cast(getdate() as date)))
and getdate()
and month(getdate()) = month(CreateDate)
and day(getdate()) > day(CreateDate)
group by Location;
This might be better done as a union with two different date ranges combined together:
-- ...
where
SalesDate between
dateadd(year, -1, dateadd(day, 1 - day(getdate()), cast(getdate() as date)))
and dateadd(year, -1, getdate())
-- ... union all ...
where
SalesDate between
dateadd(day, 1 - day(getdate()), cast(getdate() as date))
and getdate()
-- ...
i want to retrieve records where a date field is set to future months
does this look correct
Select * from table1 WHERE
datesetto >MONTH(dateadd(dd, -1, GetDate())))
select * from tablename where month(columndate)>month(getdate()) and
year(columndate)>=year(getdate())
SELECT * FROM table1
WHERE datesetto >= DATEADD(month, DATEDIFF(month, 0, getdate())+1, 0)
Explanation:
DATEDIFF(month, 0, getdate()) calculates how many months have passed since 1900-01-01.
DATEADD(month, DATEDIFF(month, 0, getdate()), 0) returns the beginning of this month.
DATEADD(month, DATEDIFF(month, 0, getdate())+1, 0) returns the beginning of next month.
Try this:
Select * from table1 WHERE
((DATEPART(MONTH,datesetto) > DATEPART(MONTH,GETDATE())
AND DATEPART(YEAR,datesetto) = DATEPART(YEAR,GETDATE()))
OR (DATEPART(YEAR,datesetto) > DATEPART(YEAR,GETDATE())))
DATEPART(Month,GETDATE()) will give the month of the current date and then you can compare it with the datesetto
Update: The above query will give data for any months greater than the current month and any month greater in the year than the current year.
Need query to get records by comparing one of it's field with different values
Here is the my table
repeated 1 means Daily
2 means Weekly
3 means Monthly
I need query to get all records which are going to Tele caste and being Tele casting by comapring current date and time.
Thank you
Do you mean something like this?
--case for daily: only need to check times
select
*
from
schedules
where
repeated = 1
--this is to compare if it starts within the next hour, may have bugs not tested
--logic is if start time - 1 hour is less than now but start time is more than now must start within the next hour
and DATEADD(day, -DATEDIFF(day, 0, dateadd(hour,startdate),-1) ), dateadd(hour,startdate),-1) ) < DATEADD(day, -DATEDIFF(day, 0, Now()), Now())
and DATEADD(day, -DATEDIFF(day, 0, startdate), startdate) > DATEADD(day, -DATEDIFF(day, 0, Now()), Now())
union
--case for weekly: is the day of the week the same, if so check times
select
*
from
schedules
where
repeated = 2
and datepart(dw,startdate) = datepart(dw,Now)
and DATEADD(day, -DATEDIFF(day, 0, dateadd(hour,startdate),-1) ), dateadd(hour,startdate),-1) ) < DATEADD(day, -DATEDIFF(day, 0, Now()), Now())
and DATEADD(day, -DATEDIFF(day, 0, startdate), startdate) > DATEADD(day, -DATEDIFF(day, 0, Now()), Now())
union
--case for monthly is the day of the month the same, if so compare times
select
*
from
schedules
where
repeated = 3
and datepart(day,startdate) = datepart(day,Now)
and DATEADD(day, -DATEDIFF(day, 0, dateadd(hour,startdate),-1) ), dateadd(hour,startdate),-1) ) < DATEADD(day, -DATEDIFF(day, 0, Now()), Now())
and DATEADD(day, -DATEDIFF(day, 0, startdate), startdate) > DATEADD(day, -DATEDIFF(day, 0, Now()), Now())
and is monthly based on date of the month , number of weeks (e.g. 4) or week of the month + weekday (e.g. second tuesday of the month)
EDIT: i think that should work where a monthly cycle is means on that day of the month every month.
The above could be modified to use a separate time column by just using that field for all time comparisons e.g.:
...
where
repeated = 3
and datepart(day,startdate) = datepart(day,Now)
and DATEADD(day, -DATEDIFF(day, 0, dateadd(hour,starttime),-1) ), dateadd(hour,starttime),-1) ) < DATEADD(day, -DATEDIFF(day, 0, Now()), Now())
and DATEADD(day, -DATEDIFF(day, 0, starttime), starttime) > DATEADD(day, -DATEDIFF(day, 0, Now()), Now())
EXPLANATION:
the normal way i would process this question as a human would be:
whats the start date
whats the repeating cycle
does startdate * any multiple of repeating cycle period = today
if so is it on now
this is a procedural, step based solution
when i think of this as a set based problem then i need to know what is the set of programs that is on now
I am allowed to add sets (union) but i cannot step through rows considering each one.. so i split it into three sets and add them together:
daily shows are on every day so i only need to check times
weekly shows are on every week on the same day, so if its weekly if the days of the week matches compare times
monthly shows are on the same day of the month every months, so if its that day of the month compare the times
hope this helps.. sorry if my explanation is crap, just trying to help :D
are you looking for this :-
Declare #Today Datetime
Select #Today = Getdate()
Select s.ProgramId
,s.ProgramName
From schedules As s With (Nolock)
Where (Cast(s.startdate As Datetime) + Cast(s.StartTime As Datetime)) >= #Today
Order By s.repeated
,s.ProgramId
Example:
SELECT column_name
FROM table_name
WHERE column_name IN (value1, value2, value3)
You mean something like that?
I have a table similar to one below. I'm trying to select only the rows where the Start Date is in the current month. Here is what I have so far, but it's not working.
SELECT *
FROM TABLE1
WHERE StartDate = MONTH(getdate())
How can I select only the values where the start date is in the current month?
Use this construct to avoid functions on the StartDate columns (like MONTH or YEAR). These functions will prevent any index or statistics being used/
SELECT *
FROM TABLE1
WHERE
StartDate >= DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
AND StartDate < DATEADD(month, 1+DATEDIFF(month, 0, GETDATE()), 0)
Any answer that puts a function on StartDate will not scale as expected. See error number 2 here. The filter is now non-sargable, and index/statistics can't be used. Every row will be looked at for a table scan.
You need to check the month of both fields
WHERE MONTH(startdate) = MONTH(getdate())
I want to display Previous month dates.May i know the query which is used to display all dates
Expected Output:
Current date = '2012-09-13'
I want to display my result as
1
2
3
4
,
,
,
,
31
these dates should come from month 8
try this:
SELECT NUMBER
FROM MASTER..SPT_VALUES
WHERE TYPE='P'
AND NUMBER BETWEEN
DATEPART(DD,DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1,0))
AND DATEPART(DD,DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()),-1))
Replcae Getdate() with your date
Please try:
;WITH DATES (date)
AS(
SELECT DATEADD(month, DATEDIFF(month, 0, dateadd(month,-1,getdate())), 0)
UNION ALL
SELECT DATEADD(DAY,1,date)
FROM DATES
WHERE DATEADD(DAY,1,date)<=DATEADD(month, DATEDIFF(month, 0, getdate()), 0)-1
)SELECT DAY(date) AS DAYS FROM DATES