How do I add the values of a column together dependant on another column - sql

It's quite a hard one to explain but probably (hopefully) an easy one to solve so I'll just explain what it is I'm trying to achieve.
I have a table where multiple logs can be entered for a day each as a seperate row, I then have a decimal as another column, I'm trying to create a summary for each day which would be something like
01/01/1900 | | 5.5
When there's one entry for the 01/01/1900 with 2.5, one with 3 in the main table so adding the values together for the day?
My only issue is adding the dates together if the dates the same, I was thinking something like
Select distinct date and joining it with a table that gets the sum of the decimal column where date is... and that's where im not too sure?
Any help would be great! thanks

If your table is named logs with data like
log_date | value
1900-01-01 | 2.5
1900-01-01 | 3
then your query is
SELECT sum(value) FROM logs GROUP BY log_date

What you're looking for is probably a GROUP BY clause.
SELECT [ yourdatecol, ] sum(yourdecimalcol) FROM yourtable
[ WHERE yourdatecol = .. ]
GROUP BY [ get_ymd_from_date(yourdatecol) | yourdatecol ] ;
With such syntax you'll get sum of row sets, selected by the same datecol value. You may also want to approximate date ( e.g. taking only Y/M/D part from it ), if date contains H/M/ss and what you want is per-day sums. Optional parts I enclosed in square brackets.

SELECT log_date,sum(value) FROM logs GROUP BY log_date

CREATE VIEW Summary
AS
SELECT
DateValue,
SUM(DecimalValue) DayTotal
FROM
EventTable
GROUP BY
DateValue;
Then
SELECT
*
FROM
Summary
WHERE
DateValue = '1900-01-01'

Try this :
SELECT CONVERT(VARCHAR, DateColumn, 103) AS OutputDate, SUM(ValueColumn) AS TotalValue
FROM YourTable
GROUP BY CONVERT(VARCHAR, DateColumn, 103)

I'm presuming a DateTime is used, lets call it logdate. I'm also presuming the other one is a decimal, lets call it logdecimal.
Using SQL server 2008 you can do (the is a type called date which is without the time-part):
SELECT
CAST(logdate as date) as TheDay,
SUM(logdecimal) as TheSum
FROM logTable
GROUP BY CAST(logdatetime as date)
Using a SQL server without the type date, maybe something like:
SELECT
CONVERT(varchar(10), logdate, 101) as TheDay,
SUM(logdecimal) as TheSum
FROM logTable
GROUP BY CONVERT(varchar(10), logdate , 101)
Regards, Olle
Edit: This one will work if it is a DateTime (including time part) you want to group as a date (not including time part). Looks like this was not the case in this question.

Related

SQL max without group by

I would like to get one row with the maximum date. I cannot use group by as I need to retrieve all data in that row.
I have this:
ID Date Country
1 05/05/2019 US
2 05/06/2019 UK
I want to get this:
ID Date Country
2 05/06/2019 UK
I've tried the below but it didn't work for me
select TOP 1 ID, Date, country
from table
order by Date desc
I don't believe you. Here is a db<>fiddle that shows three different interpretations of the date in your sample data:
as a string
as mm/dd/yyyy
as dd/mm/yyyy
All three of them produce the same result.
I suspect that your actual data is more complicated and you have oversimplified the example for the question. Further, my suspicion is that the date column is stored as a string rather than a date.
As a string, you might have some hidden characters that affect the sorting (such as leading spaces).
If this is the case, fix the data type and your code will work.
This depends on what DB system you are using.
In Microsoft SQL server, you can use row_number() function:
select top 1 *
from facts
order by ROW_NUMBER() over (order by dateKey)
Can you try this?
select Top 1 ID,Date, country from table where date = max(date)
First set the DATE or DATETIME Datatype in your [Date] column
then try this code:
SELECT TOP 1 ID, [Date] , country FROM TableName ORDER BY Date DESC
SELECT ID,Date,Country from TableName Where Date = MAX(Date) AND Rownum <= 1

SQL: select datetime values prior to that date based on it's value

I want to select rows for a field MRD which is declared as date where it is prior for that date only.
So
(case when sum (transPoints) > 4 and MRD is that same date then 4
So if a row has a date of today, I want the case when to be triggered when the transaction points are bigger than 4 against all columns with the same date.
As you can imagine the date field will be different against many rows.
Based on what I can understand from your question, it seems that the GROUP BY clause may be what you're looking for. If your date column is in the correct format then you may have to use something like:
SELECT CAST(DateColumn as DATE)
FROM YourTable
GROUP BY CAST(DateColumn as DATE)

How to rearrange the value of column

I have a table (tblDates). In this table I have two column (Date,Age) . Now I want If I add new date in this table then Age column rearranged there values.
Table - tblDates
Date Age
--------------------
12/01/14 5
12/02/14 4
12/03/14 3
12/04/14 2
12/05/14 1
If I add New date i.e., 12/06/14 then I want result like this
Table - tblDates
Date Age
--------------------
12/01/14 6
12/02/14 5
12/03/14 4
12/04/14 3
12/05/14 2
12/06/14 1
I may be reading too much into your question, but if your goal is to compute the age (in days) from a given date (today?) to the date stored in your tables, then you'll be better off using the DATEDIFF function and computing the value when you query it each time.
For example:
-- Option 1: Compute when you query it each time in the query you require it
SELECT d.[Date], DATEDIFF(dd, d.[Date], CONVERT(DATE, GETDATE())) as [Age]
FROM tblDates AS d
You can also define the Age column on your table as a Computed Column if it will be used frequently enough, or wrap the table in a View to embed this computation:
-- Option 2: Compute at query time, but build the computation into the table definition
CREATE TABLE [dbo].[tblDates] (
[Date] DATE NOT NULL,
[AgeInDaysComputed] AS (DATEDIFF(dd, [Date], CONVERT(DATE, GETDATE())) )
)
GO
-- Option 3: Compute at query time, but require caller interact with a different object
-- (view) to get the computation
CREATE VIEW [dbo].[vwDates]
AS
SELECT d.[Date], DATEDIFF(dd, d.[Date], CONVERT(DATE, GETDATE())) as [AgeInDays]
FROM dbo.tblDates AS D
GO
One note regarding the GETDATE function: you need to be aware of your server timezone, as GETDATE returns the date according to your server's local timezone. As long as your server configuration and user's configurations are all in the same timezone, this should provide the correct result.
(If the age in days is what you're trying to compute, you may want to edit your question to better reflect this intent for the benefit of future readers, as it is quite different from "rearranging the value of columns")
Pull the values that you want out when you query, not when you insert data. You seem to want:
select d.*, row_number() over (order by date desc) as age
from tblDates d;
Otherwise, your insert operation will become very cumbersome, requiring changes to all the rows in the table.

How to group by a date column by month

I have a table with a date column where date is stored in this format:
2012-08-01 16:39:17.601455+0530
How do I group or group_and_count on this column by month?
Your biggest problem is that SQLite won't directly recognize your dates as dates.
CREATE TABLE YOURTABLE (DateColumn date);
INSERT INTO "YOURTABLE" VALUES('2012-01-01');
INSERT INTO "YOURTABLE" VALUES('2012-08-01 16:39:17.601455+0530');
If you try to use strftime() to get the month . . .
sqlite> select strftime('%m', DateColumn) from yourtable;
01
. . . it picks up the month from the first row, but not from the second.
If you can reformat your existing data as valid timestamps (as far a SQLite is concerned), you can use this relatively simple query to group by year and month. (You almost certainly don't want to group by month alone.)
select strftime('%Y-%m', DateColumn) yr_mon, count(*) num_dates
from yourtable
group by yr_mon;
If you can't do that, you'll need to do some string parsing. Here's the simplest expression of this idea.
select substr(DateColumn, 1, 7) yr_mon, count(*) num_dates
from yourtable
group by yr_mon;
But that might not quite work for you. Since you have timezone information, it's sure to change the month for some values. To get a fully general solution, I think you'll need to correct for timezone, extract the year and month, and so on. The simpler approach would be to look hard at this data, declare "I'm not interested in accounting for those edge cases", and use the simpler query immediately above.
It took me a while to find the correct expression using Sequel. What I did was this:
Assuming a table like:
CREATE TABLE acct (date_time datetime, reward integer)
Then you can access the aggregated data as follows:
ds = DS[:acct]
ds.select_group(Sequel.function(:strftime, '%Y-%m', :date_time))
.select_append{sum(:reward)}.each do |row|
p row
end

SQL How to convert date DD-MM-YYYY to MM-YYYY and retrieve most recent records?

Hi I have to retrieve from my table most recent records that match a given MM-YYYY, but the date field in the table is DD-MM-YYYY, how do I get this done?
Thank you very much
Best Regards
Ignacio.
How many of the most recent records do you need?
Could you not query for all the dates in the relevant month, order by the dates, and then only select the results you need from the top of the list.
For example:
SELECT TOP(1) *
FROM your_table
WHERE date_time_field >= '20120101'
AND date_time_field < '20120201'
ORDER BY date_time_field DESC
This would select the most recent record from January of this year.
Change the number inside the TOP() statement to change the number of results returned, or leave it off altogether and take comfort in the fact that your results are ordered.
SELECT * FROM `your`.`schemaTableNames` WHERE your_coulumn_name LIKE "%-MM-YYYY";
should give you the matching records, as you wrote that you want to retrieve.
Have you tried using DateDiff(month, date1, date2) == 0 in your where clause?
This assumes that you can convert both values to DATETIME. If you only have the year and the month, every month has day 01.
to convert a date to desire format you can use style to retrive the records date formats
The following works:
right(select convert(varchar, <date field>, 110), 7)
The full query would look someting like this:
select *
from table
where right(select convert(varchar, <date field>, 110), 7) = 'MM-YYYY'