2014-12-07 31 views
1

我有查詢一個的兩個結果是:SQL以匹配表

amount | percent 
100 | 10 
200 | 20 
300 | 30 
400 | 40 

和第二個是:

sales 
10 
20 
110 
120 
210 
220 
310 
320 

有沒有辦法讓smthing這樣的:

sales      | percent 
30 (this is sum below 100) | 10 
230(this is sum between 100 and 200) | 20 
430(this is sum between 200 and 300) | 30 
630(this is sum between 300 and 400) | 40 

我想用PHP數組和循環來做,但我更喜歡不發送很多請求到服務器。有什麼建議麼?

+0

使用數組和循環實際上是避免額外的請求。 – 2014-12-07 13:45:02

+0

Bonatoc我打算髮送儘可能多的百分比數據請求,與哪裏clos,所以它會增加它 – funny 2014-12-07 13:50:30

+0

你可以讓表結構更清晰嗎? – 2014-12-07 20:35:06

回答

1

子查詢將執行查詢多次,它是沒有好 這將是更好的做用PHP 這樣的(而不是查詢我有$第一和$ 2排列)

$first = array(
    array(
     'amount' => 100, 
     'percent' => 10 
    ), 
    array(
     'amount' => 200, 
     'percent' => 20 
    ), 
    array(
     'amount' => 300, 
     'percent' => 30 
    ), 
    array(
     'amount' => 400, 
     'percent' => 40 
    ) 
); 
$second = array(
    array(
     'sales' => 10 
    ), 
    array(
     'sales' => 20 
    ), 
    array(
     'sales' => 110 
    ), 
    array(
     'sales' => 120 
    ), 
    array(
     'sales' => 210 
    ), 
    array(
     'sales' => 220 
    ), 
    array(
     'sales' => 310 
    ), 
    array(
     'sales' => 320 
    ) 
); 

$result = array(); 
$second_len = count($second); 
$s=0; 
for ($i=0,$len=count($first); $i < $len; $i++) { 
    $sum = 0; 
    for (;$s < $second_len; $s++) { 
     if ($second[$s]['sales'] <= $first[$i]['amount']) { 
      $sum += $second[$s]['sales']; 
     } else { 
      break; 
     } 
    } 
    $result[] = array(
     'sales' => $sum, 
     'percent' => $first[$i]['percent'] 
    ); 
} 

var_dump($result); 
1

首先,使用相關子查詢,查找第二個結果集中每行的正確百分比。然後彙總由:

select percent, sum(sales) 
from (select q2.*, 
      (select q1.percent 
       from query1 q1 
       where q1.amount >= q2.sales 
       order by q1.amount desc 
       limit 1 
      ) as percent 
     from query2 q2 
    ) q 
group by percent; 
+0

它給出了一個錯誤:where子句中的未知列'q.amount' – funny 2014-12-07 14:07:53

+0

@funny。 。 。那應該是'q2.sales'。 – 2014-12-07 17:17:05

1

你說你有兩個「查詢結果」。我猜他們來自桌子。因此,假設您有以下兩個表:

thresholds 
---------- 
amount | percent 
100 | 10 
200 | 20 
300 | 30 
400 | 40 

sales 
----- 
amount 
10 
20 
110 
120 
210 
220 
310 
320 

,你可以用這個查詢得到結果:

SELECT 
    SUM(sales_amount) sales 
    ,threshold_percent percent 
FROM (
    SELECT 
    s.amount sales_amount 
    ,t.amount threshold_amount 
    ,t.percent threshold_percent 
    FROM sales s 
    INNER JOIN thresholds t 
    ON t.amount > s.amount 
    LEFT JOIN thresholds t2 
    ON t2.amount < t.amount 
    AND t2.amount > s.amount 
    WHERE t2.amount IS NULL 
) sales_percents 
GROUP BY threshold_amount 

您可以點擊這裏查詢:SQLFiddle

這應該運行相當快只要您在thresholds.amountsales.amount上有索引。

+0

不是這樣,他們來自6個不同的表格。 – funny 2014-12-07 16:02:21

+0

@funny然後,您可以(1)通過用適當的子查詢替換表或者(2)使用臨時表來替換建議的查詢。無可否認,如果涉及的查詢代價高昂或複雜,則可能會更好地按照其他人的建議在應用程序代碼中執行計算。 – abl 2014-12-07 16:06:00