2014-02-20 119 views
1

我有數據這樣的分組:MySQL查詢通過contigious外鍵值

+----+-------------------------+----------+----------+ 
| ID |  DateReceived  | Quantity | VendorID | 
+----+-------------------------+----------+----------+ 
| 1 | 2010-08-09 06:53:44.783 |  2 |  1 | 
| 2 | 2010-08-01 13:31:26.893 |  1 |  1 | 
| 3 | 2010-07-26 07:52:29.403 |  2 |  1 | 
| 4 | 2011-03-22 13:31:11.000 |  1 |  2 | 
| 5 | 2011-03-22 13:31:11.000 |  1 |  2 | 
| 6 | 2011-03-22 11:27:01.000 |  1 |  2 | 
| 7 | 2011-03-18 09:04:58.000 |  1 |  1 | 
| 8 | 2011-12-17 08:21:29.000 |  1 |  3 | 
| 9 | 2012-08-10 10:55:20.000 |  9 |  3 | 
| 10 | 2012-08-02 20:18:10.000 |  5 |  1 | 
| 11 | 2012-07-12 20:44:36.000 |  3 |  1 | 
| 12 | 2012-07-05 20:45:29.000 |  1 |  1 | 
| 13 | 2013-03-22 13:31:11.000 |  1 |  2 | 
| 14 | 2013-03-22 13:31:11.000 |  1 |  2 | 
+----+-------------------------+----------+----------+ 

我想通過DateReceived對數據進行排序,總結了Quantity。但是,只要它們相鄰(當按DateReceived排序時),我想要將Quantity總和爲VendorID,如下面的示例輸出。

+----------+----------+ 
| VendorID | Quantity | 
+----------+----------+ 
|  1 |  5 | 
|  2 |  3 | 
|  1 |  1 | 
|  3 |  10 | 
|  1 |  9 | 
|  2 |  2 | 
+----------+----------+ 

我認爲答案與變量有關,但我不知道如何去做。

什麼是MySQL查詢來生成所需的輸出?

注意:我問exact same thing here但是對於MS Sql,我現在需要這個用於MySQL。

+0

你是怎麼得到'| | 1 | 9 |'行?請解釋。 –

+0

@ PM77-1通過將'VendorID'的'Quantity'字段相加1.(行ID 10-12) – Icode4food

回答

0
select 
VendorID, 
SUM(Quantity) 
from (
select 
t.*, 
@grn := if(@prev != VendorID, @grn + 1, @grn) as grn, 
@prev := VendorID 
from 
t 
, (select @grn := 0, @prev := null) var_init 
order by DateReceived 
) sq 
GROUP BY grn 

但您的預期輸出是錯誤的。你可以通過執行看到這只是這一點:

select 
t.*, 
@grn := if(@prev != VendorID, @grn + 1, @grn) as grn, 
@prev := VendorID 
from 
t 
, (select @grn := 0, @prev := null) var_init 
order by DateReceived 

導致:整個查詢的

| ID |     DATERECEIVED | QUANTITY | VENDORID | GRN | @PREV := VENDORID | 
|----|---------------------------------|----------|----------|-----|-------------------| 
| 3 |  July, 26 2010 07:52:29+0000 |  2 |  1 | 0 |     1 | 
| 2 | August, 01 2010 13:31:26+0000 |  1 |  1 | 0 |     1 | 
| 1 | August, 09 2010 06:53:44+0000 |  2 |  1 | 0 |     1 | 
| 7 | March, 18 2011 09:04:58+0000 |  1 |  1 | 0 |     1 | 
| 6 | March, 22 2011 11:27:01+0000 |  1 |  2 | 1 |     2 | 
| 4 | March, 22 2011 13:31:11+0000 |  1 |  2 | 1 |     2 | 
| 5 | March, 22 2011 13:31:11+0000 |  1 |  2 | 1 |     2 | 
| 8 | December, 17 2011 08:21:29+0000 |  1 |  3 | 2 |     3 | 
| 12 |  July, 05 2012 20:45:29+0000 |  1 |  1 | 3 |     1 | 
| 11 |  July, 12 2012 20:44:36+0000 |  3 |  1 | 3 |     1 | 
| 10 | August, 02 2012 20:18:10+0000 |  5 |  1 | 3 |     1 | 
| 9 | August, 10 2012 10:55:20+0000 |  9 |  3 | 4 |     3 | 
| 13 | March, 22 2013 13:31:11+0000 |  1 |  2 | 5 |     2 | 
| 14 | March, 22 2013 13:31:11+0000 |  1 |  2 | 5 |     2 | 

結果:

| VENDORID | SUM(QUANTITY) | 
|----------|---------------| 
|  1 |    6 | 
|  2 |    3 | 
|  3 |    1 | 
|  1 |    9 | 
|  3 |    9 | 
|  2 |    2 |