我在使用DISTINCT和GROUP BY的查询中仍然遇到问题,但仍收到有关该行的重复行。 GBelow是查询:
SELECT DISTINCT ms.id AS ms_id, ms.identity, ms.timezone, ms.language,
ms.country, ms.dst, ms.mobile, ms.voice, ms.email, ms.firstname, ms.lastname, ms.gender, ms.address_1,
ms.address_2, ms.city, ms.state, ms.zipcode, ms.dateofbirth,
ms.custom_field_1, ms.custom_field_2, ms.custom_field_3, ms.custom_field_4,
ms.custom_field_5, ms.carrier, ms.stamp AS ms_stamp,
ss.id AS ss_id, ss.last_response_text, ss.stamp AS ss_stamp,
c.id AS c_id, c.name, c.stamp AS c_stamp,
c.messenger_account, c.keyword, c.community, ms.hash
FROM tbl_messenger_subscriber_session ss
JOIN tbl_messenger_subscriber ms ON ss.subscriber = ms.id
LEFT JOIN tbl_messenger_subscriber_category c ON c.id = ss.subscriber_category
WHERE ms.custom_field_1 = 'Middlesex' AND ss.subscriber_category IN ('23607','23634')
GROUP BY ms_id, c.messenger_account
并且输出看起来像这样
ms_id | other columns
1636088 | xxxxxxxxxxxx
1636088 | xxxxxxxxxxxx
1636090 | xxxxxxxxxxxx
1636090 | xxxxxxxxxxxx
1636336 | xxxxxxxxxxxx
1636337 | xxxxxxxxxxxx
预期的输出看起来像这样
ms_id | other columns
1636088 | xxxxxxxxxxxx
1636090 | xxxxxxxxxxxx
1636336 | xxxxxxxxxxxx
1636337 | xxxxxxxxxxxx
在查询DISTINCT和GROUP BY时,我做错了什么吗?
如果您想每ms_id
排一行,则您的代码没有这样做。 SELECT DISTINCT
返回all列的唯一组合。
一种执行所需操作的方法使用row_number()
:
SELECT x.*
FROM (SELECT . . .,
ROW_NUBMER() OVER (PARTITION BY ms.id ORDER BY ms.id) as seqnum
FROM tbl_messenger_subscriber_session ss JOIN
tbl_messenger_subscriber ms
ON ss.subscriber = ms.id LEFT JOIN
tbl_messenger_subscriber_category c
ON c.id = ss.subscriber_category
WHERE ms.custom_field_1 = 'Middlesex' AND
ss.subscriber_category IN ('23607', '23634')
) x
WHERE seqnum = 1;