简体   繁体   中英

SQL query for stacked bar chart

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?

  • one bar for each CategoryID
  • within each CategoryID, I want the number of products that use bags, bottles or jars (Substring in Unit column)

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

The first step will be to create a flag for bags, bottles, and jars. This can be done in either SQL or Power BI.

For SQL, use a query like this:

SELECT *
    ,   CASE
            WHEN Products.Unit LIKE '%bag%' THEN 'Bag'
            WHEN Products.Unit LIKE '%bottle%' THEN 'Bottle'
            WHEN Products.Unit LIKE '%jar%' THEN 'Jar'
            ELSE 'Other'
        END AS 'UnitFlag'
FROM dbo.Products

For Power BI, use DAX to create a new column with this formula:

UnitFlag = IF(IFERROR(SEARCH("bag", Products[Unit]), -1) > 1, "Bag",
    IF(IFERROR(SEARCH("Bottle", Products[Unit]), -1) > 1, "Bottle",
        IF(IFERROR(SEARCH("Jar", Products[Unit]), -1) > 1, "Jar",
            "Other"
        )
    )
)

Then just configure your stacked chart as shown below.

图形

From here, you can change a couple of settings to make the graph look a little nicer; for instance, changing the X-Axis to be treated as Categorical instead of Continuous and hiding the "Other" category if you don't want that visible.

It sounds like you want to learn about aggregation:

select categoryID, 
       reverse(left(reverse(unit), charindex(' ',reverse(unit))-1)) as Unit_type, -- gets the last word of `UNIT`
       count(*) as Total_Products
from Products
group by categoryID, 
         reverse(left(reverse(unit), charindex(' ',reverse(unit))-1))

What this will do is count all of the rows and group by Unit type and categoryID. Try it, see what happens.

I would suggest that you learn about aggregation sooner rather than later, it's incredibly powerful.

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