2012-05-03 18 views
0

使用SQL分組,我怎麼能給值日期,由每家公司進行分組?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是公司特定的。

+0

什麼是確定公司一天邏輯? – Taryn

+0

@bluefeet它看起來像表中最早的一天是1,然後從那裏列舉。 – Matthew

+0

@MatthewPK這是我的猜測太多,但他們需要澄清的要求 – Taryn

回答

1

我會先拿到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

+0

感謝馬特 - 什麼是有效的代碼呢?我在桌上有大約5000家公司,因此手工找到最短日期將會很困難。 –

+0

哈 - 你發佈代碼之前我可以發表評論。謝謝,讓我看看! –

+1

@MatthewPK僅供參考 - 有更好的資源比w3​​schools.com – Taryn