SQL为解析函数中的每个值查找最小数目

时间:2018-09-18 17:21:56

标签: sql sql-server function analytical

我正在使用Microsoft SQL Server。我想编写一个仅具有分析功能的查询(例如不使用分组依据)

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

  • MIN(客户编号),计数(代码),私人
  • MIN(客户编号),计数(代码),业务

例如,我制作了两个表

enter image description here

在此示例中,它仅适用于Customer_number = 1,2的行,如下所示:

Mat output(propGpu);
Mat planes[2];
split(output,planes);
Mat mag;
magnitude(planes[0],planes[1],mag);
mag.convertTo(mag, CV_8U, 255, 0);

我写道:

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

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

如果有人可以帮助我定购方法,并解释错误的地方,那就太好了。

1 个答案:

答案 0 :(得分: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

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