简体   繁体   中英

SQL query to make difficult data aggregation

I need to extract data from a MySQL database to make a report, and I'm stuck in something I've never seen before. Suppose I have data on 4 hardware components, and a customer can make requests for ram, ip, cpu and backup components. Every record of my table has a "quantity" field and a "component" field, so if a customer wishes to buy 4 ram quantity will get the value 4 and component the value ram.

Each record can be an activation of the product subscription (with component and quantity equals to NULL) or the request for components (one record per type of component, so if a customer wants to buy 4 ram and 1 ip I will have an activation, the request with 4 ram and a request with 1 ip ).

In the aggregation report I need a column for each component, so a cpu column, an ip column etc. I need to populate the values with NULL if the customer has just registered or did not order components of that kind, or with the quantity if he bought one of these components.

Let's make it practical:

  • John registers
  • John buys 1 ip
  • John buys 4 ram

What I want is something like:

  • 1st record, cpu,ip,ram,backup set to null
  • 2nd record, ip set to 1 and the others to NULL
  • 3rd record, ram set to 4 and others to NULL

How can I accomplish something like that? I somehow need to make the possible values of component column as new different columns, and fill them with the values of quantity column.

Why not use cases on the possible components?

select
    CASE 
        WHEN component='ip' 
        THEN quantity
        ELSE NULL 
    END as 'ip',
    CASE 
        WHEN component='ram' 
        THEN quantity
        ELSE NULL 
    END as 'ram',
    CASE 
        WHEN component='cpu' 
        THEN quantity
        ELSE NULL 
    END as 'cpu',
    CASE 
        WHEN component='backup' 
        THEN quantity
        ELSE NULL 
    END as 'backup'
from table;

I hate to say it but this database design can create confusion because you're grouping 'objects' that you shouldn't. For example, you should have a table of just registrations and one table of orders with parentIds of the orderers..but I digress. If I understand your question correctly:

To solve this problem, you'll need sub or multiple queries for example one to select * where ip is Null AND cpu is Null AND ram is NULL, then sum the result and insert into quantity column where id = this id

one to select where cpu is Null, one to select where others are null then sum the result and insert into quantity column where id = this id,

… and so on.

Then parse the output from each query.

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