简体   繁体   English

在SQL中按日期添加数据排序

[英]Adding data ordering by date in SQL

How to add values separately by date in order. 如何按日期分别添加值。 Suppose there're several values with same date with a particular field. 假设在特定字段中有多个具有相同日期的值。 I wamt to sum up those data and want to have a particular row with one date. 我想总结一下这些数据,并希望有一个带有日期的特定行。 oredered by date. 按日期排序。

So let's say you have some data like this: 因此,假设您有一些像这样的数据:

DATE              VALUE
------------------------------
2017-01-01        100
2017-02-01        50
2017-01-01        75
2017-02-01        25

What it sounds like you want to do is take those 4 rows and combine them down to 2, one for 2017-01-01 and one for 2017-02-01, is that correct? 听起来您想做的是将这4行合并为2,一列用于2017-01-01,一列用于2017-02-01,对吗?

If so, you just need to do an INSERT with a SELECT and GROUP BY on the origin data. 如果是这样,您只需要对原始数据执行SELECT和GROUP BY的INSERT。

So if I am trying to INSERT to Test_Table_One and my data was in Origin_Table_One, I would do: 因此,如果我尝试对Test_Table_One进行插入并且我的数据在Origin_Table_One中,则可以这样做:

INSERT INTO Test_Table_One
SELECT DATE, SUM(VALUE)
FROM Origin_Table_One
GROUP BY DATE

Does tht make sense? 有道理吗?

Try this: 尝试这个:

   create table #temp
(
    Date date,
    Sum bigint
)


create table #tempVarious
( 
    Date date,
    value bigint
)

insert into #tempVarious
values
    (cast(getdate() as date), 1),
    (cast(getdate() as date), 1),
    (cast(getdate() as date), 3),
    (cast(getdate() as date), 5),
    (cast(getdate() as date), 6),
    (cast(getdate() as date), 8),
    (cast(getdate() as date), 3),
    (cast(dateadd(day,-1,getdate()) as date), 1),
    (cast(dateadd(day,-1,getdate()) as date), 3),
    (cast(dateadd(day,-1,getdate()) as date), 6),
    (cast(dateadd(day,-1,getdate()) as date), 2),
    (cast(dateadd(day,-1,getdate()) as date), 1)

insert 
into #temp
select date
    , sum(value)
from #tempVarious
group by date

select * 
from #temp

It seems you are very new in SQL, please read these two tutorials about GROUP BY https://www.w3schools.com/sql/sql_groupby.asp and ORDER BY https://www.w3schools.com/sql/sql_orderby.asp 看来您是SQL的新手,请阅读有关GROUP BY https://www.w3schools.com/sql/sql_groupby.aspORDER BY https://www.w3schools.com/sql/sql_orderby.asp的这两个教程

SELECT DATE_COLUMN, SUM(VALUE_COLUM)
FROM TABLE
GROUP BY DATE_COLUMN
ORDER BY DATE_COLUMN

A variant in case you want to order by descending 如果您想通过降序订购的变体

ORDER BY DATE_COLUMN DESC

In case your column is of type DateTime and you have different times in a single date 如果您的列的类型为DateTime并且您在单个日期中具有不同的时间

SELECT CAST(DATE_COLUMN AS DATE) AS DC, SUM(VALUE_COLUM)
FROM TABLE
GROUP BY CAST(DATE_COLUMN AS DATE)
ORDER BY DC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM