0

我有两张桌子CompanyCompanyLike

公司赞

  1. ID
  2. 评级之星
  3. 数数
  4. 公司编号

Company 和 CompanyLike 有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
4

3 回答 3

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
于 2013-02-13T08:50:26.510 回答
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想到)从组中选择一个。


小提琴。结果:

RATINGSTAR  COMPANYID   COMPANYNAME COUNT
1           101         CompanyB    1
2           959         CompanyC    1
5           5636        CompanyA    2
于 2013-02-13T08:17:35.853 回答
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 ;

结果:_

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

.

解释

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

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

享受。

于 2013-02-13T08:26:40.940 回答