[英]Select distinct on Left Join for only one column
我正在嘗試列出每個客戶購買的產品,但是如果他們在不同的場合購買相同的商品,我希望將其排除在外。 這是我到目前為止的內容:
Select c.field_id_33 AS email, o.order_id, Group_concat(o.entry_id) AS Products,group_concat(t.title),group_concat(t.url_title) from finn_cartthrob_order_items o
LEFT JOIN finn_channel_data c
ON c.entry_id=o.order_id
LEFT JOIN finn_channel_titles t
ON o.entry_id=t.entry_id
GROUP BY email
這產生了:
基本上,無論他們購買了多少次,只要他們購買了一次,我只需要列出一次該產品。 我該怎么做?
您可以在group_concat函數中使用DISTINCT
,使用Group_concat謹防這一事實,即默認限制為將1024個字符分組,但是可以增加
Select c.field_id_33 AS email, o.order_id,
Group_concat(DISTINCT o.entry_id) AS Products,
group_concat(DISTINCT t.title),
group_concat(DISTINCT t.url_title)
from finn_cartthrob_order_items o
LEFT JOIN finn_channel_data c
ON c.entry_id=o.order_id
LEFT JOIN finn_channel_titles t
ON o.entry_id=t.entry_id
GROUP BY email
從文檔開始,結果被截斷為group_concat_max_len系統變量給定的最大長度,該變量的默認值為1024。盡管返回值的有效最大長度受的值限制,但可以將其設置為更高的值。 max_allowed_packet的。 在運行時更改group_concat_max_len的值的語法如下,其中val是無符號整數:
SET [全球| SESSION] group_concat_max_len = val;
就像可以在select
關鍵字之后使用distinct
,您也可以在聚合函數(包括group_concat
)內使用它,以將每個group_concat
值僅聚合一次:
Select
c.field_id_33 AS email, o.order_id,
Group_concat(DISTINCT o.entry_id) AS Products,
group_concat(DISTINCT t.title),
group_concat(DISTINCT t.url_title)
from finn_cartthrob_order_items o
LEFT JOIN finn_channel_data c
ON c.entry_id=o.order_id
LEFT JOIN finn_channel_titles t
ON o.entry_id=t.entry_id
GROUP BY email
您是否考慮過在PARTITION BY上使用ROW_NUMBER?
這是一個樣本。
SELECT *
FROM (SELECT order_id,
entry_id,
ROW_NUMBER() OVER (PARTITION BY entry_id
ORDER BY entry_id) AS ProductCount
FROM finn_cartthrob_order_items
) AS Products
WHERE ProductCount = 1
ORDER BY Products.order_id
這應該為每個entry_id返回第一個order_id和entry_id。 它的功能在概念上與此類似。
SELECT TOP 1 *
FROM finn_cartthrob_order_items
WHERE entry_id = @Specific_entry_id
您可能需要在Over(Partition By)中包括一些左連接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.