简体   繁体   English

如何在一个sql表中计算来自同一字段的不同行

[英]how to count different rows from the same field in one sql table

hi I have one table which I am trying to get the count of different rows on the same row field for example I a have this rows 嗨,我有一个表,我试图获取同一行字段上不同行的计数,例如我有此行

Function field1 field2 field3
'dog'    1      1      5
'dog'    1      1      5
'cat'    1      1      5
'dog'    1      2      6

The output for this table should be: 该表的输出应为:

Function count
'dog'    2
'cat'    1

because there are two different rows for 'dog' (some of the field are different) and one row for 'cat' 因为“狗”有两行不同(某些字段是不同的),而“猫”有一行

thank you so much 非常感谢

Assuming that you want to count rows identical based on a given subset of fields, this would be: 假设您要基于给定的字段子集对相同的行进行计数,则为:

 SELECT func, COUNT(*) FROM (
     SELECT DISTINCT func, field1, field2 FROM yourtable
 ) AS tmp GROUP BY func;

This first distincts all the rows, so you get 这首先区分所有行,因此您得到

'dog'    1      1      5
'cat'    1      1      5
'dog'    1      2      6

and then counts the first field, thus giving 2 and 1. 然后计算第一个字段,从而得到2和1。

You can even do something like 你甚至可以做类似的事情

 SELECT func, COUNT(*) AS different, SUM(total) AS total FROM (
     SELECT   func, field1, field2, field3, COUNT(*) AS total 
            FROM yourtable
     GROUP BY func, field1, field2, field3
 ) AS tmp GROUP BY func;

which will give: 这将给:

 func   different   total
 dog    2           3
 cat    1           1

This should give you the results you are looking for: 这应该为您提供所需的结果:

Select  Function, Count(*) As Count
From
(
    Select  Distinct
            Function,
            Field1,
            Field2,
            Field3
    From    YourTable
) As A
Group By Function

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

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