How to group orders by Date - sql

I have a order details table and I want to find the sum of price by each date and display them as
For Ex
count sum date
5 619.95 2015-11-19
3 334.97 2015-11-18
4 734.96 2015-11-18
5 1129.95 2015-11-18
I have written the query for getting the count and sum as
select count(id), sum([price])
from [OrderDetails]
where [date]between '2015-10-29 05:15:00' and '2015-11-09 00:01:00'
group by datepart(day,[date])
But not able to achieve with date. How can it be done?

You need to include what you are grouping on in the SELECT portion of your query:
select count(id), sum([price]), datepart(day,[date]) as [date]
from [OrderDetails]
where [date] between '2015-10-29 05:15:00' and '2015-11-09 00:01:00'
group by datepart(day,[date]);

It seems like your column called date has both a date and time component. I would suggest converting it to a date, for both the select and group by:
select count(id), sum(price), cast([date] as date) as thedate
from OrderDetails
where [date] between '2015-10-29 05:15:00' and '2015-11-09 00:01:00'
group by cast([date] as date)
order by thedate;
Note: date is a poor name for a column, because it is the name of a built-in type.

Related

SQL query result needs to be summed

Code is
select customerid, count(campaignid) as T, Convert (varchar, CreatedOn,23) from customerbenefits
where campaignid='6EDBB808-1A91-4B1D-BE1D-27EF15C5D4C7'
and createdon between '2019-09-01' and '2019-10-01'
group by customerid,CreatedOn
having count(campaignid)>1
order by createdon desc
Result is
-- id / count /time
--18655680-3B5E-4001-1984-00000000 / 12 /2019-09-30
--18655680-3B5E-4001-1984-00000000 / 7 / 2019-09-30
--18655680-3B5E-4001-1984-00000000 / 6 / 2019-09-30
I want result as
-- id / count / time
-- 18655680-3B5E-4001-1984-00000000 / 25/ 2019-09-30
I want it grouped to time filter and sum counts.
How can I change my query?
Use two levels of aggregation:
select customerid, dte, sum(T)
from (select customerid, count(*) as T, convert(varchar(255), CreatedOn, 23) as dte
from customerbenefits
where campaignid = '6EDBB808-1A91-4B1D-BE1D-27EF15C5D4C7' and
createdon >= '2019-09-01' and
createdon < '2019-10-01'
group by customerid, CreatedOn
having count(*) > 1
) t
group by customerid, dte
order by createdon desc ;
Notice that I changed the date comparisons so midnight on 2019-10-01 is not included in the data for September.

sql query group by date range

I have table with below data -
StartDate EndDate Amount
2/1/2016 4/30/2016 2.265
2/1/2016 12/31/2099 16.195
5/1/2016 12/31/2099 37.75
I am trying to write a query to sum the amount on date range and give me below result
StartDate EndDate Amount
2/1/2016 4/30/2016 18.46
5/1/2016 12/31/2099 53.945
The result needs to be distinct date range with amount summed for that date range. As in above example, row 2 has dates that overlap row 1 and 3. So the row 2 amount needs to be added in row 1 and row 3.
I am writing this query on sql server 2012, Please advise on what approach I should take.
Below is query to generate sample data
SELECT * INTO #tmp_GridResults_1
FROM (
SELECT N'2016-02-01 00:00:00.000' AS [StartDate], N'2016-04-30 00:00:00.000' AS [EndDate], N'2.265' AS [Amount] UNION ALL
SELECT N'2016-02-01 00:00:00.000' AS [StartDate], N'2099-12-31 00:00:00.000' AS [EndDate], N'16.195' AS [Amount] UNION ALL
SELECT N'2016-05-01 00:00:00.000' AS [StartDate], N'2099-12-31 00:00:00.000' AS [EndDate], N'37.75' AS [Amount] ) t;
SELECT [StartDate], [EndDate], [Amount]
FROM #tmp_GridResults_1
I don't think you'll be able to group with both StartDate and EndDate. However, if you use just StartDate and Amount you can try this:
select StartDate,sum(Amount) as Amount from #tmp_GridResults_1 group by StartDate
This will give you the grouping of Amount by StartDate.
From my previews comment i think you want to group by StartDate, in that case you can use:
SELECT
mt.StartDate,
SUM(Amount) AS 'Amount'
FROM MyTable mt
WHERE mt.StartDate BETWEEN
'2016-05-18 00:00:00.000' AND '2016-06-20 00:00:00.000' --your date range
GROUP BY StartDate
However you need to specify in your question how you want to group them, because with 2 date fields you can group the following ways:
GROUP BY StartDate --groups records that have the same StartDate
GROUP BY EndDate --groups records that have the same EndDate
GROUP BY StartDate, EndDate --groups records that have same StartDate and EndDate
Also with 2 date fields your date range can vary a lot.
WHERE StartDate BETWEEN #sd AND #ed --will get records whose start date is inside the provided range
WHERE EndDate BETWEEN #sd AND #ed --will get records whose end date is inside the provided range
WHERE StartDate >= #sd AND EndDate <= #ed -- will get records that started and ended inside the provided date range
WHERE StartDate BETWEEN #sd AND #ed OR EndDate BETWEEN #sd AND #ed
--this last one will get records whose StartDate or EndDate are inside the provided date range
based on this you can build the query that you need, but with the provided data in your question its still ambiguous what you want to achieve, you need to be more specific and provide more data in order to produce an exact answer to your question.
One more thing to add is that if you take into account time it will not group them if the date is the same but time is different i.e.
'2016-05-18 00:00:00.000'
'2016-05-18 01:01:01.001'
--these dates will not be grouped
Below query will give the required result :-
select StartDate,EndDate,SUM(Amount) over (partition by StartDate) AS Amount into #t1
from table_name
select StartDate,EndDate,SUM(Amount) over (partition by EndDate) AS Amount into #t2
from table_name
select * from (
select distinct P.StartDate,P.EndDate,P.Amount from (
select StartDate,MIN(EndDate) EndDate,Amount from #t1
group by StartDate,Amount) P
JOIN (
select MIN(StartDate) StartDate,EndDate,Amount from #t2
group by EndDate,Amount) Q on P.StartDate=Q.StartDate OR P.EndDate=Q.EndDate
where P.Amount>=Q.Amount
UNION
select distinct P.StartDate,P.EndDate,P.Amount from (
select MIN(StartDate) StartDate,EndDate,Amount from #t2
group by EndDate,Amount) P
JOIN (
select StartDate,MIN(EndDate) EndDate,Amount from #t1
group by StartDate,Amount) Q on P.StartDate=Q.StartDate OR P.EndDate=Q.EndDate
where P.Amount>=Q.Amount
) A
Just Replace table_name by the table for which you want result, Let me know in case of any confusion

Join operation on two tables retrieving dates

My first query, retrieving date and hours worked from work_details of a given employee number in a given date.
SELECT date,
SEC_TO_TIME( SUM( TIME_TO_SEC( `total_hours` ) ) ) AS total
FROM `work_details`
WHERE employee_id='28'
and date between '2012-02-01'
and '2012-02-29'
GROUP BY DATE ORDER BY DATE
and the Second query retrieving date from table holy_date:
SELECT holy_date
from holiday
where holy_date between '2012-02-01' and '2012-02-29'
I need to combine results of the two queries in the correct date order.
I tried union operation,but dint get result.
How can I do it?
There are a few ways to achieve what you want.
This is not the documented way of doing it. But this should work.
SELECT date, total
FROM
(
SELECT date, SEC_TO_TIME( SUM( TIME_TO_SEC( `total_hours` ) ) ) AS total
FROM `work_details`
WHERE employee_id='28' AND date BETWEEN '2012-02-01' AND '2012-02-29'
GROUP BY date
UNION ALL
(
SELECT holy_date AS date, NULL AS total
FROM holiday
WHERE holy_date BETWEEN '2012-02-01' AND '2012-02-29'
)
) AS t
GROUP BY date
ORDER BY date

How to count number of records per day?

I have a table in a with the following structure:
CustID --- DateAdded ---
396 2012-02-09
396 2012-02-09
396 2012-02-08
396 2012-02-07
396 2012-02-07
396 2012-02-07
396 2012-02-06
396 2012-02-06
I would like to know how I can count the number of records per day, for the last 7 days in SQL and then return this as an integer.
At present I have the following SQL query written:
SELECT *
FROM Responses
WHERE DateAdded >= dateadd(day, datediff(day, 0, GetDate()) - 7, 0)
RETURN
However this only returns all entries for the past 7 days. How can I count the records per day for the last 7 days?
select DateAdded, count(CustID)
from Responses
WHERE DateAdded >=dateadd(day,datediff(day,0,GetDate())- 7,0)
GROUP BY DateAdded
select DateAdded, count(CustID)
from tbl
group by DateAdded
about 7-days interval it's DB-depending question
SELECT DateAdded, COUNT(1) AS NUMBERADDBYDAY
FROM Responses
WHERE DateAdded >= dateadd(day,datediff(day,0,GetDate())- 7,0)
GROUP BY DateAdded
This one is like the answer above which uses the MySql DATE_FORMAT() function. I also selected just one specific week in Jan.
SELECT
DatePart(day, DateAdded) AS date,
COUNT(entryhash) AS count
FROM Responses
where DateAdded > '2020-01-25' and DateAdded < '2020-02-01'
GROUP BY
DatePart(day, DateAdded )
If your timestamp includes time, not only date, use:
SELECT DATE_FORMAT('timestamp', '%Y-%m-%d') AS date, COUNT(id) AS count FROM table GROUP BY DATE_FORMAT('timestamp', '%Y-%m-%d')
You could also try this:
SELECT DISTINCT (DATE(dateadded)) AS unique_date, COUNT(*) AS amount
FROM table
GROUP BY unique_date
ORDER BY unique_date ASC
SELECT count(*), dateadded FROM Responses
WHERE DateAdded >=dateadd(day,datediff(day,0,GetDate())- 7,0)
group by dateadded
RETURN
This will give you a count of records for each dateadded value. Don't make the mistake of adding more columns to the select, expecting to get just one count per day. The group by clause will give you a row for every unique instance of the columns listed.
select DateAdded, count(DateAdded) as num_records
from your_table
WHERE DateAdded >=dateadd(day,datediff(day,0,GetDate())- 7,0)
group by DateAdded
order by DateAdded
Unfortunately the best answer here IMO is a comment by #Profex on an incorrect answer , but the solution I went with is
SELECT FORMAT(DateAdded, 'yyyy-MM-dd'), count(CustID)
FROM Responses
WHERE DateAdded >= dateadd(day,datediff(day,0,GetDate())- 7,0)
GROUP BY FORMAT(DateAdded, 'yyyy-MM-dd')
ORDER BY FORMAT(DateAdded, 'yyyy-MM-dd')
Note that I haven't tested this SQL since I don't have the OP's DB , but this approach works well in my scenario where the date is stored to the second
The important part here is using the FORMAT(DateAdded, 'yyyy-MM-dd') method to drop the time without losing the year and month , as would happen if you used DATEPART(day, DateAdded)
When a day among last 7 days, has no record means, the following code will list out that day with count as zero.
DECLARE #startDate DATE = GETDATE() - 6,
#endDate DATE = GETDATE();
DECLARE #daysTable TABLE
(
OrderDate date
)
DECLARE #daysOrderTable TABLE
(
OrderDate date,
OrderCount int
)
Insert into #daysTable
SELECT TOP (DATEDIFF(DAY, #startDate, #endDate) + 1)
Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, #startDate)
FROM sys.all_objects a
CROSS JOIN sys.all_objects b;
Insert into #daysOrderTable
select OrderDate, ISNULL((SELECT COUNT(*) AS OdrCount
FROM [dbo].[MyOrderTable] odr
WHERE CAST(odr.[CreatedDate] as date) = dt.OrderDate
group by CAST(odr.[CreatedDate] as date)
), 0) AS OrderCount from #daysTable dt
select * from #daysOrderTable
RESULT
OrderDate     OrderCount
2022-11-22     42
2022-11-23     6
2022-11-24     34
2022-11-25     0
2022-11-26     28
2022-11-27     0
2022-11-28     22
SELECT DATE_FORMAT(DateAdded, '%Y-%m-%d'),
COUNT(CustID)
FROM Responses
GROUP BY DATE_FORMAT(DateAdded, '%Y-%m-%d');

Group by month in SQLite

I have an SQLite database which contains transactions, each of them having a price and a transDate.
I want to retrieve the sum of the transactions grouped by month. The retrieved records should be like the following:
Price month
230 2
500 3
400 4
it is always good while you group by MONTH it should check YEAR also
select SUM(transaction) as Price,
DATE_FORMAT(transDate, "%m-%Y") as 'month-year'
from transaction group by DATE_FORMAT(transDate, "%m-%Y");
FOR SQLITE
select SUM(transaction) as Price,
strftime("%m-%Y", transDate) as 'month-year'
from transaction group by strftime("%m-%Y", transDate);
You can group on the start of the month:
select date(DateColumn, 'start of month')
, sum(TransactionValueColumn)
from YourTable
group by
date(DateColumn, 'start of month')
Try the following:
SELECT SUM(price), strftime('%m', transDate) as month
FROM your_table
GROUP BY strftime('%m', transDate);
Use the corresponding page in SQLite documentation for future references.
SELECT
SUM(Price) as Price, strftime('%m', myDateCol) as Month
FROM
myTable
GROUP BY
strftime('%m', myDateCol)
This another form:
SELECT SUM(price) AS price,
STRFTIME('%Y-%m-01', created_at) as created_at
FROM records
GROUP BY STRFTIME('%Y-%m-01', created_at);
Another way is to substring the year and the month from the column and group by them. Assuming the format it's like 2021-05-27 12:58:00 you can substract the first 7 digits:
SELECT
substr(transDate, 1, 7) as YearMonth
SUM(price) AS price
FROM
records
GROUP BY
substr(transDate, 1, 7);
In Sqlite, if you are storing your date in unixepoch format, in seconds:
select count(myDate) as totalCount,
strftime('%Y-%m', myDate, 'unixepoch', 'localtime') as yearMonth
from myTable group by strftime('%Y-%m', myDate, 'unixepoch', 'localtime');
If you are storing the date in unixepoch format, in milliseconds, divide by 1000:
select count(myDate/1000) as totalCount,
strftime('%Y-%m, myDate/1000, 'unixepoch', 'localtime') as yearMonth
from myTable group by strftime('%Y-%m, myDate/1000, 'unixepoch', 'localtime');