简体   繁体   English

SQL添加计数列基于相同的表并按另一列分组

[英]SQL add count column based on same table and grouped by another column

I appreciate this is a bit weird but I need to do this this way because the next data reporting steps relay on data in this specific format. 我知道这有点奇怪,但是我需要这样做,因为接下来的数据报告步骤将以这种特定格式传递数据。 Let say I have a table like: 假设我有一个像这样的表:

ID | Type   | Item  
----------------------
1  | red    | apple  
2  | red    | apple  
3  | green  | apple  
4  | red    | berry  
5  | red    | berry  
6  | green  | banana  
7  | yellow | lemon   

what I need now is to add a column to the SELECT * query that will in each record tell me how many records there are in the WHOLE query that have the same type. 我现在需要的是在SELECT *查询中添加一列,这将在每条记录中告诉我,在整个查询中有多少条记录具有相同类型。 So the output that I am looking for would be: 因此,我正在寻找的输出将是:

ID | Type   | Item   | count of type  
-------------------------------------
1  | red    | apple  |  4  
2  | red    | apple  |  4    
3  | green  | apple  |  2  
4  | red    | berry  |  4  
5  | red    | berry  |  4  
6  | green  | banana |  2  
7  | yellow | lemon  |  1  

I know I can do a subquery but the actual data is much more complicated (formulas and joins all over the place) and every time I add a sub query it makes the whole query a bit messy. 我知道我可以进行子查询,但是实际数据要复杂得多(在各处都有公式和联接),每次添加子查询时,整个查询都会有些混乱。 So just wondering if I could do this count somehow "directly" in the main query? 因此,只是想知道我是否可以在主查询中以某种方式“直接”进行计数? or maybe you guys have yet another idea. 也许你们还有另一个主意。 what do you think. 你怎么看。 I am working on dashDB 我正在使用dashDB

You can use partition by: 您可以通过以下方式使用分区:

select ID, Type, Item, count(ID) over(partition by Type) as CountOfType
From table

You can GROUP By Type and Item to get count of each Item and Type 您可以按类型和项目分组以获取每个项目和类型的计数

SELECT t1.ID, t1.Type, t1.Item, t2.CountType
FROM tableName t1
JOIN ( SELECT Type, Item,COUNT(*) As CountType 
       FROM tableName
       GROUP BY Type, Item
     ) As t2

ON t1.Type = t2.Type AND t1.Item = t2.Item

您可以使用解析函数,将以下内容Count(*) over (partition by Type) as countOfType添加到您的SELECT查询Count(*) over (partition by Type) as countOfType

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

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