[Solved] SQL query for stacked bar chart

EverSQL Database Performance Knowledge Base

SQL query for stacked bar chart

Database type:

In my project I'm trying to write a query to fetch data for a stacked bar graph. Instead of explaining the schema of my DB (which would be lengthy), I found a similar analogy which I can port to my DB later.

On this page, run the query

SELECT * FROM [Products]

In the table, if I want to select data for stacked bar graph as below, how do I form the query?

Sorry, I'm not able to demonstrate substantial research effort in this, as I'm not even able to visualize what the SELECT clause would look like. I tried to check if we can use AS in WHERE clause and then do a COUNT on it. But that does not seem to be correct syntax.

I'm going to be running the actual query on MS SQL Server through PowerBI

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
The optimized query:
SELECT
        * 
    FROM
        [Products]

Related Articles



* original question posted on StackOverflow here.