mysql - SQL 将数字分配给日期,按值分组

标签 mysql sql date join

使用 SQL,我如何给按每个公司分组的日期赋值?

当前表:

Date            Company          Employees

2012-04-28      Apple, Inc.      7543
2012-04-27      Apple, Inc.      7510
2012-04-26      Apple, Inc.      7484

2012-04-28      Google, Inc.     11303
2012-04-27      Google, Inc.     11300
2012-04-26      Google, Inc.     11280
2012-04-25      Google, Inc.     11278
2012-04-24      Google, Inc.     11254

所需的表:

Date            company_day      Company          Employees

2012-04-28      3                Apple, Inc.      7543
2012-04-27      2                Apple, Inc.      7510
2012-04-26      1                Apple, Inc.      7484

2012-04-28      5                Google, Inc.     11303
2012-04-27      4                Google, Inc.     11300
2012-04-26      3                Google, Inc.     11280
2012-04-25      2                Google, Inc.     11278
2012-04-24      1                Google, Inc.     11254

company_day 的值从每个公司的最早日期开始。 company_day 是公司特定的。

最佳答案

我会先获取每家公司的 MIN 日期。

然后您可以JOIN该查询的结果并简单地显示它与日期列之间的差异。

SELECT 
    MyTable.[Date]
    ,DATEDIFF(MyTable.[Date], MinTable.[MinDate]) + 1 AS Company_Day
    ,MyTable.[Company]
    ,MyTable.[Employees]
FROM
    MyTable
JOIN
    (
    SELECT 
        MIN(b.[Date]) AS MinDate
        , b.[Company] 
    FROM 
       MyTable b 
    GROUP BY 
        b.[Company]
    ) AS MinTable
        ON MinTable.[Company] = MyTable.[Company]

类似的东西。此代码未经测试,但应该接近。
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_datediff
http://www.w3schools.com/sql/func_datediff_mysql.asp

关于mysql - SQL 将数字分配给日期,按值分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10439711/

相关文章:

php - 在 MySQL 查询中转换 $_POST 变量

mysql - 从远程服务器连接到 Amazon EC2 上的 mysql

sql - 将数据复制到同一个表中或从同一个表中复制数据,并将复制的数据中某一列的值更改为指定值

javascript - 如何在 JavaScript 中验证包含 “00:07 PM” 的日期?

json - +0000 在 twitter API 返回的日期上下文中是什么意思?

Javascript 的日期对象 toLocaleTimeString 添加一个小时

mysql - 根据另一个表中的行类型选择行

mySQL如何将NULL显示为0

php - 使用 mysqli 从数组插入 MySQL

sql - 替换文本表达式中的多个 ID