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

时间:2012-05-03 21:41:13

标签: 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是特定于公司的。

1 个答案:

答案 0 :(得分:2)

我会先得到每家公司的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