您似乎只需要客户 1 和 2,我将其解释为您只需要编号最低的私人客户和最低编号的企业客户。
您不想使用分组依据。
SELECT * FROM
(
SELECT
--number each row, order by customer number, "group" by business type
ROW_NUMBER() OVER(PARTITION BY c.customer_type ORDER BY c.customer_number) rown,
--it isn't totally clear if you want the count of codes per customer or per type
count(s.code) OVER (partition by c.customer_number) AS count_codes_by_cust,
count(s.code) OVER (partition by c.customer_type) AS count_codes_by_type,
customer_type
FROM
customers c
INNER JOIN
subscribers s
ON s.customer_number = c.customer_number
) c
WHERE rown = 1 --cust #1 and cust#2 both have a rown of 1
请注意,为了清楚起见,我已将连接留给订阅者并计算代码 - 您最初尝试缺少的关键概念是使用 WHERE 将输出限制为仅两行
您的第一次尝试也可以修改为产生要求:
SELECT * FROM
(
SELECT
min(c.customer_number) OVER (partition by c.customer_type) AS min_cust,
c.customer_number,
--it isn't totally clear if you want the count of codes per customer or per type
count(s.code) OVER (Partition by c.customer_number) AS count_codes_by_cust,
count(s.code) OVER (Partition by c.customer_type) AS count_codes_by_type,
customer_type
FROM
customers c
INNER JOIN
subscribers s
ON s.customer_number = c.customer_number
)d
WHERE
min_cust = customer_number
但是这种方法的一个缺陷是它给出了多行,因为加入客户和订阅者会导致客户编号重复,并且您最终会得到不止一行,其中where min_cust = customer number
为真: min(customer_number) over(...) 有选择“1”和“2”作为您的最小客户数量,但由于加入订阅者,1 出现 3 次,2 出现两次
row_number 方法在这方面有所不同 = 每个 customer_type 只有一行的行号可以为 1,因此您只能获得与不同类型的客户一样多的行。更一般地说,如果您有一个表,例如,存储了文档的多个日期版本,并且您只需要每个文档的最新版本,您可以:
SELECT * FROM (
SELECT
doc.*,
ROW_NUMBER() OVER(PARTITION BY filename ORDER BY filedate DESC) --latest is numbered 1
FROM
documents
)doc WHERE rown = 1
要更详细地查看操作,请仅突出显示并运行内部查询,以查看外部查询正在操作的原始数据。