简体   繁体   中英

SQL query cast from a group

I'm trying to make a query whit a 'cast group by' - output.

But not quit sure how to tackle this or even to start (I think i need cast and group by but not sure).

I have some code below which hopefully explains what I'm trying to do. Could somebody help me to make a query to have the correct output?

CREATE TABLE buyers
(
    id int,
    buyer_name varchar(20)
);
    
INSERT INTO buyers
VALUES (1, 'harry'), (2, 'zoe'), (3, 'rose');
    
CREATE TABLE grocery
(
    id int,
    name VARCHAR(20),
    id_buyers int
);
    
INSERT INTO grocery
VALUES (1, 'milk', 1), (2, 'milk', 1), (3, 'ham', 1), (4, 'bread', 2),
       (5, 'bread', 2), (6, 'bread', 2), (6, 'milk', 2), (7, 'milk', 2),
       (8, 'ham', 3);

CREATE TABLE wanted_output
(
    name VARCHAR(20),
    stuffed_lists VARCHAR(20)
);
    
INSERT INTO wanted_output
VALUES ('harry', '2x milk, 1x ham'), ('zoe', '3x bread, 2x milk'),
       ('rose', '1x ham ');

EDIT: at this point I have this (not working):

    SELECT 
      buyers.buyer_name,
      COALESCE(
        STUFF(
          (SELECT ' , ' + 
                  CAST( grocery.name AS varchar(max)) 
          from grocery 
          where grocery.id_buyers = buyers.id 
          FOR XML PATH('')
        ), 1, 2, '' ),'') 
      
      AS wanted_output
    FROM buyers

nvm afther some fideling:

    SELECT 
      buyers.buyer_name,
      COALESCE(
        STUFF(
          (SELECT ' , ' + cast(count(*) as varchar(4)) + ' x ' +
                  CAST( grocery.name AS varchar(max)) 
          from grocery 
          where grocery.id_buyers = buyers.id 
          group by grocery.name
          FOR XML PATH('')
        ), 1, 2, '' ),'') 
      
      AS wanted_output
    FROM buyers

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