This is my database and fiddle setup:
CREATE TABLE PRODUCTS (
NAME varchar(20),
PRODUCT_ID int(3)
);
CREATE TABLE PAYMENT (
NAME varchar(20),
PAYMENT_ID int(4)
);
INSERT INTO PRODUCTS (NAME, PRODUCT_ID)
VALUES
("Apple", 1),
("Banana", 2),
("Watermelon", 3),
("Bread", 4),
("Milk", 5),
("Cake", 6),
("Candy", 7),
("Butter", 8),
("Carrot", 9),
("Tomato", 10);
INSERT INTO PAYMENT (NAME, PAYMENT_ID)
VALUES
("Banana", 85),
("Apple", 94),
("Banana", 94),
("Candy", 85),
("Banana", 105);
https://www.db-fiddle.com/f/5jsGYfWZ6pnzgf62Z5FA8L/0
I'm thinking I have to do some Count(CASE statement within here).
I saw something about pivots, but not sure about that?
Yes you are right, that is a possibility
I use IF when there is only one option.
SELECT
p.NAME
,SUM(IF(PAYMENT_ID = 85,1,0)) '85'
,SUM(IF(PAYMENT_ID = 94,1,0)) '94'
,SUM(IF(PAYMENT_ID = 105,1,0)) '105'
FROM PRODUCTS p LEFT JOIN PAYMENT pa ON p.NAME = pa.NAME
GROUP BY p.NAME;
There Reference between the two tables should be the id and not the name, the name maybe unique, but numbers need less space than text.
CREATE TABLE PRODUCTS ( NAME varchar(20), PRODUCT_ID int(3) ); CREATE TABLE PAYMENT ( NAME varchar(20), PAYMENT_ID int(4) ); INSERT INTO PRODUCTS (NAME, PRODUCT_ID) VALUES ("Apple", 1), ("Banana", 2), ("Watermelon", 3), ("Bread", 4), ("Milk", 5), ("Cake", 6), ("Candy", 7), ("Butter", 8), ("Carrot", 9), ("Tomato", 10); INSERT INTO PAYMENT (NAME, PAYMENT_ID) VALUES ("Banana", 85), ("Apple", 94), ("Banana", 94), ("Candy", 85), ("Banana", 105);
\n✓ \n\n✓ \n\n✓ \n\n✓ \n
SELECT p.NAME ,SUM(IF(PAYMENT_ID = 85,1,0)) '85' ,SUM(IF(PAYMENT_ID = 94,1,0)) '94' ,SUM(IF(PAYMENT_ID = 105,1,0)) '105' FROM PRODUCTS p LEFT JOIN PAYMENT pa ON p.NAME = pa.NAME GROUP BY p.NAME;
\nNAME | 85 | 94 | 105 \n:--------- | -: | -: | --: \nApple | 0 | 1 | 0 \nBanana | 1 | 1 | 1 \nBread | 0 | 0 | 0 \nButter | 0 | 0 | 0 \nCake | 0 | 0 | 0 \nCandy | 1 | 0 | 0 \nCarrot | 0 | 0 | 0 \nMilk | 0 | 0 | 0 \nTomato | 0 | 0 | 0 \nWatermelon | 0 | 0 | 0 \n
db<>fiddle here
MySQL has a convenient shortcut. I recommend:
SELECT p.NAME,
SUM(pa.PAYMENT_ID = 85) as payment_85,
SUM(pa.PAYMENT_ID = 94) as payment_94,
SUM(pa.PAYMENT_ID = 105) as payment_105
FROM PRODUCTS p LEFT JOIN
PAYMENT pa
ON p.NAME = pa.NAME
GROUP BY p.NAME;
Of course, if you don't care about products with no payments, you only need one table:
SELECT pa.NAME,
SUM(pa.PAYMENT_ID = 85) as payment_85,
SUM(pa.PAYMENT_ID = 94) as payment_94,
SUM(pa.PAYMENT_ID = 105) as payment_105
FROM PAYMENT pa
GROUP BY pa.NAME;
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.