Skip to content
Advertisement

How can I create summaries across columns?

I have an existing application database table supporting an application, and I’ve been tasked with adding another feature. Currently, we have a build table that stores information about product builds. This table will not be changed, but it contains a primary key, BuildId, that will be used to cross reference the new table.

The new table contains a list of errors and warnings that occurred during the build. It will contain a reference to the primary key from the other table, which will also be the primary key in this table. Then, the user can select the errors and warnings that applied to the build.

Can I create summaries across the columns? For example, if I need to get the total number of errors on a build, I have to include each of the columns in the query. This can get pretty bloated since there are currently 12 and 10 errors and warnings, respectively.

I’m adding a sql fiddle that shows a trimmed down version of my current table, and one of the queries I’m trying to build.

I plan to run a number of different queries against the dataset. Counts of warnings/errors, queries to find specific errors (such as Error1 = true), etc. An example query (which is also seen in the fiddle link below) is:

This returns the correct analysis, but as you can imagine, it will get messy with all of the columns. I’ve considered creating a function to clean up the query, but I’m not sure if I can pass a whole row to a function without specify each column individually.

I’d appreciate any help here. Can this reasonably done using a function, stored procedure, or sql syntax with which I’m unfamiliar? Is my design flawed?

Thanks!

Editing to mention that each of the columns maps to a predetermined error. For example, Error1 might map to “Part doesn’t fit correctly”. So, we shouldn’t run into a case where there are more errors than available fields. At that time, we’d just add a new column.

http://sqlfiddle.com/#!18/cba91/9

Advertisement

Answer

You can just use CROSS APPLY and conditional aggregation as the following:

Which will returns:

Here is a db<>fiddle

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement