开发者

The sum of a DateTime column

开发者 https://www.devze.com 2023-03-21 12:04 出处:网络
Using T-SQL, how do you find the sum of DateTime values for x amount of records? Example: id(int) |name(varchar) |TimeInWomb(datetime)

Using T-SQL, how do you find the sum of DateTime values for x amount of records?

Example:

id(int) |  name(varchar) |  TimeInWomb(datetime)
---------------------------------------
 id1    |     name1      |     TiW1
 id2    |     name2      |     TiW2
 id3    |     name1      |     TiW3
 id4    |     name1      |     TiW4
  .     |       .        |      .
  .     |       .        |      .
  .     |       .        |    开发者_开发知识库  .

I want to find the sum of the TimeInWomb's where name = name1.

Thanks.

EDIT:

I admit, in hindsight that was a pretty bad example which I've now changed. By "sum" I mean the sum of the hours/days/weeks/months of all the values where name = name1.

ANSWER:

You can't sum datetimes.


I noticed in your edit that you changed your "date of birth" column to "time in womb". Those are two very different concepts. "date of birth" is a SINGLE point in time, where "time in womb" is a DURATION of time. Which of these two concepts are you trying to represent?

  • If you're trying to represent a single point in time, then doing a "sum" doesn't make any sense. You can't have a sum of two points in time.
  • If you're trying to represent a duration of time, then you shouldn't be using a DATETIME column. DATETIME is used to refer to a single point in time. You should either have two DATETIME columns (a start and an end), or you should have number column (number of seconds, or something similar).

Either way something is conceptually wrong here and we can't give you an answer until you get things sorted out. Some sample data with expected output would help dramatically.

Edit:

Since you're trying to represent a duration of time (the time in the womb), then you need to either have two DATETIME columns (time of conception and time of birth, for example) or a single number column (seconds in womb, for example). The second option is easier to work with, but the first option gives you more flexibility.

Let's assume that you've got a SecondsInWomb column that is a number. The answer to your original question would be:

SELECT SUM(SecondsInWomb) FROM table WHERE name = 'name1'

That will tell you the total amount of seconds spent in the womb for that name.


if you are only setting the equivalent of a time for instance you could use SQL's defaults to accomplish your goal by doing the following:

sum(datediff(minutes,'1900-01-01 00:00:00',TimeInWomb)

If you do not set part of a date time function, you would get the MS SQL default for the other portion. The MS SQL default is 1900-01-01 00:00:00. If you only set the date, the time is set to 00:00, if you set the time, the date becomes 1900-01-01.

I hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消