简体   繁体   English

计算SQL中的组

[英]Count over a Group in SQL

I need to create a query that counts over a GROUP BY clause. 我需要创建一个对GROUP BY子句进行计数的查询。 Specifically, over the Order_ID and SUB_ID columns and counts the number of Product_IDs per Order_ID and SUB_ID . 具体来说,在Order_IDSUB_ID列上,对每个Order_IDSUB_IDProduct_IDs数量进行计数。

It should look like this: 它看起来应该像这样:

在此处输入图片说明

However, the data is set up a little on the odd side and the only way to get the information (minus the Count column of course) is with: 但是,数据的设置有点奇怪,获取信息的唯一方法(当然要减去Count列)是:

SELECT
    tbl1.Order_Id
    ,tbl1.Sub_Id
    ,tbl1.Product_Id
    ,tbl1.Product_Value
    ,tbl2.Product_Owner
    ,tbl2.Owner_Id

FROM
tbl1 AS tbl1
LEFT OUTER JOIN
    tbl2 AS tbl2 ON tbl1.Order_Id=tbl2.Order_Id AND tbl1.Sub_Id=tbl2.Sub_Id

How would I add such a column? 如何添加这样的列?

I think you just need GROUP BY : 我认为您只需要GROUP BY

SELECT tbl1.Order_Id, tbl1.Sub_Id,
       COUNT(tbl1.Product_Id)
FROM tbl1 LEFT OUTER JOIN
     tbl2
     ON tbl1.Order_Id = tbl2.Order_Id AND tbl1.Sub_Id = tbl2.Sub_Id
GROUP BY tbl1.Order_Id, tbl1.Sub_Id;

Because the query is returning rows only from tbl1 and using a LEFT JOIN , you should be able to do: 因为查询仅从tbl1返回行并使用LEFT JOIN ,所以您应该能够:

SELECT tbl1.Order_Id, tbl1.Sub_Id,
       COUNT(tbl1.Product_Id)
FROM tbl1 
GROUP BY tbl1.Order_Id, tbl1.Sub_Id;

EDIT: 编辑:

I see, that is sample data. 我知道,这是示例数据。 In that case, you probably just want row_number() : 在这种情况下,您可能只需要row_number()

SELECT tbl1.Order_Id, tbl1.Sub_Id, tbl1.Product_Id, tbl1.Product_Value,
       tbl2.Product_Owner, tbl2.Owner_Id
       ROW_NUMBER() OVER (PARTITION BY tbl1.Order_Id, tbl1.Sub_Id ORDER BY tbl1.Product_Id) as seqnum
FROM tbl1 LEFT OUTER JOIN
     tbl2 
     ON tbl1.Order_Id = tbl2.Order_Id AND
        tbl1.Sub_Id = tbl2.Sub_Id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM