简体   繁体   中英

How to bulid a report with a total and breakout columns with SQL Server and Reporting Services

I have a data structure where I have two tables Alpha and Beta and they are one to many. For the sake of an example let's say that table alpha has a column for "State" and table B has "Colors you like" and you can pick more than one. I would like to build a report that has columns like this:

STATE          TOTAL     RED     GREEN     BLUE
Alaska         5         1       3         1
Florida        2         2       2         0
New York       10        5       8         1

The column TOTAL would be a count of the records in Alpha and as you can see due to the one to many relationship the sum of the colors can exceed the count. I suppose it could be less as well if people didn't like colors.

How would you build a report like this. I'll be using SQL Server and Reporting Services in .NET so it could either be a complex query that I just dump into a data table report or a less complex query with some counting and totaling done by the report. I just don't really know the best way to tackle this.

Since you don't know which colors are going to be the columns you should use the Matrix Control

You'll need to set up the query

SELECT 
    a.State,
    b.ColorName,
    COUNT(b.ColorID) ColorCount
FROM
    alpha a
    LEFT JOIN beta b
    ON a.id = b.a_id
GROUP BY 
    a.State,
    b.ColorName

Just drag state for the rows, color for the columns and ColorCount for the data ( Count(ColorID) will display in the data field))

Note: The LEFT JOIN and Count(ColorID) instead of Count(*) are required if you want a 0 value to appear correctly.

If you did know the colors you could use PIVOT or the sum case technique

SELECT state SUM(CASE WHEN Color = 'RED' THEN 1 ELSE 0 END) as Red, ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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