如何获取表中相同记录的总和/数量

时间:2013-02-13 08:08:19

标签: sql sql-server sql-server-2008 tsql

我有两张表CompanyCompanyLike

CompanyLike

  1. 编号
  2. RatingStar
  3. 计数
  4. Companyid
  5. 公司和公司似乎有1 to Many关系。一家公司可以有很多喜欢

    像公司一样的公司将会是这样的

    +----------------------------+
    | ID  RatingStar   Companyid |
    +----------------------------+
    | 1      5           5636    |
    | 2      5           5636    |
    | 3      1           101     |
    | 4      2            959    |
    +----------------------------+
    

    现在,我希望得到评级明星的数量,即RatingStar为5的次数,以及2对每个Companyid的次数

    我目前的工作是

     SELECT RatingStar AS RatingStar,com.id AS Companyid , c.Id AS Id ,
            com.Name AS CompanyName, Count(RatingStar) AS ratingCount
       FROM CompanyReviewLike AS c
       INNER JOIN Company AS com ON com.id = c.Companyid
       GROUP BY RatingStar ,com.Name , com.id ,c.Id
    

3 个答案:

答案 0 :(得分:1)

我认为您只想从查询中删除c.id

select RatingStar as RatingStar,com.id as Companyid  ,com.Name as  
         CompanyName ,  

 Count(RatingStar) as Count,MIN(c.ID) as Id
     from CompanyReviewLike as c
   inner join Company as com on com.id = c.Companyid
 Group By 
 RatingStar ,com.Name , com.id

由于每一行都有不同的c.id,如果将其包含在分组中,则每个组只包含一行。如果您想在结果中包含一个 id值,请选择合适的聚合(MINMAX注意)以从组中选择一个


Fiddle。结果:

RATINGSTAR  COMPANYID   COMPANYNAME COUNT
1           101         CompanyB    1
2           959         CompanyC    1
5           5636        CompanyA    2

答案 1 :(得分:1)

如果你只关注评级星5和2计数

,请检查一下
SELECT COM.Name AS CompanyName, C.RatingStar AS RatingStar, COUNT(*) AS RatingCount
FROM CompanyLike AS C
INNER JOIN Company AS COM ON COM.id = C.Companyid
GROUP BY C.RatingStar ,COM.Name 
HAVING C.RatingStar IN (5,2)

检查最新的

SELECT C.id,COM.Name AS CompanyName, C.RatingStar AS RatingStar, COM.RatingCount AS RatingCount
    FROM CompanyLike C
    INNER JOIN ( SELECT COM.Name AS CompanyName,C.CompanyId, C.RatingStar AS RatingStar, COUNT(*) AS RatingCount
                FROM CompanyLike AS C
                INNER JOIN Company AS COM ON COM.id = C.Companyid
                GROUP BY C.RatingStar ,COM.Name ,C.CompanyId
                HAVING C.RatingStar IN (5,2)) COM
    ON C.RatingStar = Com.RatingStar AND C.CompanyId = COM.id

答案 2 :(得分:0)

您需要透视数据。不要说你的桌子是:

create table compa ( id int, name varchar(10) );
create table likes (idComp int, rating int);
create table rates ( id int);

然后你的查询是:

select * 
from (
    select r.id as rate, 
         c.id as comp,
         l.idComp as n
  from compa c
  cross join rates r
  left join likes l
     on l.rating = r.id
        and c.id = l.idComp
) as src
PIVOT
(
count( n )
FOR rate IN ( [1], [2], [3], [4], [5] )
) as pvt ;

results

| COMP | 1 | 2 | 3 | 4 | 5 |
----------------------------
|    1 | 3 | 1 | 0 | 0 | 1 |
|    2 | 0 | 3 | 0 | 0 | 0 |

<强>解释

选择表之间的内部查询连接结果以获取原始数据的速率。 Pivot子句计算数据并将行数据移动到列以仅按公司获取列。

通知费率交叉加入以获得公司的所有费率,也离开加入以获得没有费率的公司。

享受。