SQL - A 列中的唯一结果基于 B 列中的特定值是最常见的值

SQL - Unique results in column A based on a specific value in column B being the most frequent value

所以我面临以下挑战:

我正在尝试从所有在商店 103(B 列)进行大部分购买的客户(A 列)获得独特的结果。

商店定义在票号的前3位。挑战在于我还要为每个客户拿到每张票。我只需要 SQL 根据在商店 103 进行大部分购买的所有唯一客户来计算和过滤结果。

A栏信息来自Table1,B栏信息来自Table2.

Example

我一直在尝试以下方法:

SELECT DISTINCT Table_1.Full_Name, Table_2.Ticket_#
FROM Table_2
LEFT OUTER JOIN Table_1
  ON Table_2.Customer_Number = Table_1.Customer_Number;

我知道我缺少 group by 或 order by 关键字,但我不知道如何在这种特殊情况下正确使用它们。

非常感谢您。

这里有三个选项。

SELECT customers.Full_Name, tickets."Ticket_#"
FROM Table_2 tickets INNER JOIN Table_1 customers
    ON customers.Customer_Number = tickets.Customer_Number INNER JOIN
    (
        SELECT Customer_Number
        FROM Table_2 tickets
        GROUP BY Customer_Number
        HAVING COUNT(CASE WHEN LEFT("Ticket_#", 3)  = '103' then 1 end)
             > COUNT(CASE WHEN LEFT("Ticket_#", 3) <> '103' then 1 end)
    ) AS m ON m.Customer_Number = customers.Customer_Number

SELECT customers.Full_Name, tickets."Ticket_#"
FROM Table_2 tickets INNER JOIN Table_1 customers
    ON customers.Customer_Number = tickets.Customer_Number
WHERE customers.Customer_Number IN (
    SELECT Customer_Number
    FROM Table2 tickets
    WHERE "Ticket_#" LIKE '103%'
    GROUP BY Customer_Number
    HAVING COUNT(*) > (
        SELECT COUNT(*)
        FROM Table2 tickets2
        WHERE tickets2.Customer_Number = tickets.Customer_Number
            AND NOT "Ticket_#" LIKE '103%' 
    )
)

WITH data AS (
    SELECT customers.Full_Name, tickets."Ticket_#"
        COUNT(CASE WHEN LEFT(tickets."Ticket_#", 3)  = '103' then 1 end)
            OVER (PARTITION BY customers.Customer_Number) AS MatchCount
        COUNT(CASE WHEN LEFT(tickets."Ticket_#", 3) <> '103' then 1 end)
            OVER (PARTITION BY customers.Customer_Number) AS NonmatchCount
    FROM Table_2 tickets INNER JOIN Table_1 customers
        ON customers.Customer_Number = tickets.Customer_Number
)
SELECT * FROM data WHERE MatchCount > NonmatchCount;