1

我正在使用 Microsoft SQL Server。我想写一个只有分析功能的查询(比如不使用 group by)

我想编写一个返回以下行的查询:

  • MIN(Customer_number), count(code), private
  • MIN(Customer_number), count(code), 业务

例如,我制作了两张桌子

在此处输入图像描述

通过这个例子,它应该只适用于 Customer_number = 1,2 的行,如下所示:

* 1,intermediate results counting,private
.
.
.
* 2, intermediate results counting, business
.
.
.

我写:

SELECT 
    MIN(subscribers.customer_number) OVER (PARTITION BY customers.customer_number, customer_type) AS cusNo,
    COUNT(subscribers.code) OVER (PARTITION BY customers.customer_number, customer_type) AS subscribes,
    customer_type
FROM
    customers 
JOIN
    subscribers ON subscribers.customer_number = customers.customer_number;

我尝试了这么多时间来了解如何返回正确的输出,为什么它不起作用并且找不到它

如果有人可以帮助我如何订购它,并解释出了什么问题,那就太好了。

4

1 回答 1

0

您似乎只需要客户 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

要更详细地查看操作,请仅突出显示并运行内部查询,以查看外部查询正在操作的原始数据。

于 2018-09-18T17:28:42.093 回答