1

使用 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 是公司特定的。

4

1 回答 1

2

我会首先得到MIN每家公司的日期。

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

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

于 2012-05-03T21:47:05.307 回答