简体   繁体   English

sql查询报告

[英]sql query for a report

I have a view which contains (among other columns) a header "name", and an item "rating" column. 我有一个视图,其中包含(除其他列之外)标题“名称”和项目“评分”列。 The view joins the header to the item table, so the name column from the header is repeated for every item. 该视图将标题连接到项目表,因此对于每个项目重复标题中的名称列。

I need to run a report on the table; 我需要在桌子上运行一个报告; ideally, I would have 5 columns in the sql result; 理想情况下,我将在sql结果中有5列; the header "name", and 4 copies of the "rating" column, where every copy of the rating column shows the count of ratings which are over a certain threshold. 标头“名称”和“评级”列的4个副本,其中评级列的每个副本都显示超过特定阈值的评级计数。 So rating column #1 will show the number of items in the table (for the item's header) which have a rating of 1 or higher, the second rating column will show the number of items in the table (for the same item's header) which have a rating of 5 or higher, and so on. 因此,等级1列将显示表中(等级为1或更高)的项目数量(第二个等级列)将显示表中(相同条目的标题)的项目数量评级为5或更高,依此类推。

I know how to get the name and 1 rating column back: 我知道如何获取名称和1个评级列:

select name, count(rating) as cnt1 from myview where rating > 1 group by name

but combining that with the other desired rating columns is failing me at the moment. 但是将其与其他所需的评级列结合起来目前使我感到失望。 Tried using a "union" clause, but that just puts multiple rows in the result list. 使用“联合”子句进行了尝试,但这只是将多行放入结果列表中。 An absolute requirement (the query has to plug into a report template, so this is very inflexible) is that I only have one row returned for every unique "name" field in the view, because otherwise the report object which is going to read the data won't know how to interpret the results. 绝对要求(查询必须插入报表模板,因此非常不灵活)是,对于视图中的每个唯一“名称”字段,我只返回一行,因为否则将要读取报表对象的报表对象。数据不知道如何解释结果。

Any tips? 有小费吗?

Update Here is some sample data: 更新这里是一些示例数据:

name, rating
myname1, 1
myname1, 1
myname1, 10
myname1, 4
myname1, 7
myname1, 3
myname1, 5
myname1, 5
myname1, 4
myname2, 2
myname2, 10
myname2, 6
myname2, 8
myname2, 5
myname2, 4
myname2, 6

And the desired output: 和所需的输出:

name, cnt1, cnt5, cnt7, cnt8
myname1, 7, 2, 1, 1
myname2, 7, 4, 2, 1

...where cnt1 = rating > 1, cnt5 = rating > 5, cnt7 = rating > 7, cnt8 = rating > 8 ...其中cnt1 =评分> 1,cnt5 =评分> 5,cnt7 =评分> 7,cnt8 =评分> 8

select name,
       sum(case when rating > 1 then 1 else 0 end) as cnt1,
       sum(case when rating > 5 then 1 else 0 end) as cnt2
       /* ... repeat as many times as needed */
    from myview
    group by name

从myview组中按名称选择名称,即SUM(等级大于1,然后1则0结束时的情况)作为cnt1,名称和,总计(等级大于5,然后1则0结束时的情况)作为myt5从myview组按名称

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

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