2014-03-26 80 views
0

我有這樣的查詢,它給我關於暢銷書商品的結果,目前它可以正常工作,但現在我只想從每個商店獲得一個產品,以便擁有不同的si對查詢計數不同的行的MySQL查詢

+--------+---------+-------+ 
| id | shop_id | count | 
+--------+---------+-------+ 
| 425030 | 38027 | 111 | 
| 291974 | 5368 | 20 | 
| 425033 | 38027 | 18 | 
| 291975 | 5368 | 12 | 
| 142776 | 5368 | 10 | 
| 397016 | 38027 |  9 | 
| 291881 | 5368 |  8 | 
+--------+---------+-------+ 

任何想法:從商店

SELECT `si`.`id`, si.shop_id, 
(SELECT COUNT(*) 
FROM `transaction_item` AS `tis` 
JOIN `transaction` as `t` 
ON `t`.`id` = `tis`.`transaction_id` 
WHERE `tis`.`shop_item_id` = `si`.`id` 
AND `t`.`added_date` >= '2014-02-26 00:00:00') 
AS `count` 
FROM `shop_item` AS `si` 
INNER JOIN `transaction_item` AS `ti` 
ON ti.shop_item_id = si.id 
GROUP BY `si`.`id` 
ORDER BY `count` DESC LIMIT 7 

這給了像畝的結果shop_id只有一個暢銷的產品?

編輯 所以我創建了一個搗鼓它 http://sqlfiddle.com/#!2/cfc4c/1

現在查詢返回賣得最好的,我希望它從shopso小提琴的結果只返回一個產品的產品應該是

+----+---------+-------+ 
| ID | SHOP_ID | COUNT | 
+----+---------+-------+ 
| 1 |  222 |  3 | 
| 4 |  333 |  2 | 
| 8 |  555 |  1 | 
| 9 |  777 |  1 | 
+----+---------+-------+ 
+0

請提供一些示例數據和期望的結果。你怎麼知道交易中的物品? –

回答

0

可能這樣的事情: -

SELECT si.shop_id, 
    SUBSTRING_INDEX(GROUP_CONCAT(CONCAT_WS(':', si.id, sub1.item_count) ORDER BY sub1.item_count DESC), ',', 1) AS `count` 
FROM shop_item AS si 
INNER JOIN 
(
    SELECT tis.shop_item_id, COUNT(*) AS item_count 
    FROM transaction_item AS tis 
    JOIN `transaction` as t 
    ON t.id = tis.transaction_id 
    AND t.added_date >= '2014-02-26 00:00:00' 
    GROUP BY tis.shop_item_id 
) sub1 
ON sub1.shop_item_id = si.id 
GROUP BY si.shop_id 
ORDER BY `count` DESC LIMIT 7 

子查詢獲取項目的計數s爲每個商店。然後,主查詢將項目ID和項目數量連接在一起,組將單個商店的所有這些連接在一起(按降序計數),然後使用SUBSTRING_INDEX獲取第一個(即第一個逗號前面的所有內容)。

您將不得不分開計數字段以分別獲取物品ID和計數(分隔符是:)。

這是對你真正想要什麼,以及沒有表聲明或數據沒有測試的幾個猜測。

編輯 - 現在測試與SQL小提琴例如: -

SELECT SUBSTRING_INDEX(`count`, ':', 1) AS ID, 
    shop_id, 
    SUBSTRING_INDEX(`count`, ':', -1) AS `count` 
FROM 
(
    SELECT si.shop_id, 
     SUBSTRING_INDEX(GROUP_CONCAT(CONCAT_WS(':', si.id, sub1.item_count) ORDER BY sub1.item_count DESC), ',', 1) AS `count` 
    FROM shop_item AS si 
    INNER JOIN transaction_item AS ti 
    ON ti.shop_item_id = si.id 
    INNER JOIN 
    (
     SELECT tis.shop_item_id, COUNT(*) AS item_count 
     FROM transaction_item AS tis 
     JOIN `transaction` as t 
     ON t.id = tis.transaction_id 
     AND t.added_date >= '2014-02-26 00:00:00' 
     GROUP BY tis.shop_item_id 
    ) sub1 
    ON sub1.shop_item_id = si.id 
    GROUP BY si.shop_id 

) sub2 
ORDER BY `count` DESC LIMIT 7; 
+0

好吧mayby這會有所幫助,我創建了一個小提琴手http://sqlfiddle.com/#!2/cfc4c/1檢查更新 – olechafm

+0

測試和修改,以給你所需的格式的數據。 – Kickstart

+0

不幸的是,它不在真正的數據庫上... – olechafm