Question

I have two tables are:

  • products (PID, RELEASEDATE, PNAME, PRICE)enter image description here
  • sells (SELLID, SELLPID, SELLUID, SELLDATE, SELLTYPE)
    enter image description here

but i have no idea how i can solve this query: Show each year total income
I have tried with inner join, left join and then group by but nothing works! Here is what i have understand from Stikel answer:

SELECT to_char(s.selldate, 'YYYY') AS "Year",
       SUM(p.price)                AS "Income"
  FROM sells AS s
  LEFT JOIN products AS p ON p.pid = s.sellpid
 GROUP BY "Year"

but it still not working!

Was it helpful?

Solution

SELECT to_char(s.SELLDATE, 'YYYY') Year, sum(p.PRICE) Income
  FROM sells s, products p
 WHERE p.PID = s.SELLPID
 GROUP BY to_char(s.SELLDATE, 'YYYY')
 ORDER BY 1

OTHER TIPS

I created the following tables in MySQL:

CREATE TABLE `products` (
  `PID` INT(11) NULL DEFAULT NULL,
  `RELEASEDATE` DATETIME NULL DEFAULT NULL,
  `PNAME` VARCHAR(50) NULL DEFAULT NULL,
  `PRICE` INT(11) NULL DEFAULT NULL
)
ENGINE=MyISAM;
INSERT INTO `products` VALUES (1,'2009-01-01 11:04:57','Secure Web',29),(3,'2011-12-10 11:05:19','Hyper Code Editor',80),(4,'2013-01-03 11:05:39','WinOSX',25);

CREATE TABLE `sells` (
  `SELLID` INT(11) NULL DEFAULT NULL,
  `SELLPID` INT(11) NULL DEFAULT NULL,
  `SELLUID` INT(11) NULL DEFAULT NULL,
  `SELLDATE` DATETIME NULL DEFAULT NULL,
  `SELLTYPE` VARCHAR(50) NULL DEFAULT NULL
)
ENGINE=MyISAM;
INSERT INTO `sells` VALUES (1,1,3,'2009-12-02 11:03:31','software'),(2,1,4,'2009-09-01 11:04:00','software'),(3,1,4,'2009-09-25 11:04:24','softare'),(4,1,1,'2010-04-14 11:04:41','update');

And insert the you can get your data with this SQL:

SELECT
  year(s.SELLDATE) AS 'Year', 
  sum(p.PRICE) AS 'Income'
FROM `sells` AS s LEFT JOIN `products` AS p 
ON p.PID=s.SELLPID 
GROUP BY year(s.SELLDATE)

Result

+------+--------+
| Year | Income |
+------+--------+
| 2009 |     87 |
| 2010 |     29 |
+------+--------+
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top