MySql Table Self Join

时间:2015-07-31 20:36:48

标签: mysql self-join

I have the table below

sku|date      |price
---|----------|-----
A1 |2015-01-10|3
A2 |2015-01-15|2
A1 |2015-01-20|5
A1 |2015-02-10|2
A2 |2015-02-10|1

I'm trying to get the count per month. I'd like to get the output below;

sku|JAN_ORDER|FEB_ORDER|JAN_TOTAL
---|---------|---------|---------
A1 |2        |1        |10
A2 |1        |1        |2

I've tried self join and left join with no success, and I'm getting a bit confused.

I get incorrect results with the code below

select s.sku, count(f.sku)
from database f, database s
where f.sku between '2015-01-01' and '2015-01-31'
and
s.sku=f.sku
group by s.sku

Please advise.

2 个答案:

答案 0 :(得分:0)

No need for joins

SELECT s.sku,
   SUM(IF(date = 'Jan', 1, 0)) AS JAN,
   SUM(IF(date = 'Feb', 1, 0)) AS Feb
FROM yourtable
GROUP BY sku

Of course, performance is going to be crappy, but since there's only 12 months, won't be terribly crappy. These sorts of transforms are invariably better done in client-side code, and just have a normal

SELECT sku, COUNT(date)
FROM yourtable
GROUP BY date

答案 1 :(得分:0)

像Marc B所说,不需要加入:

SQL Fiddle

MySQL 5.6架构设置

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
    Here is some code:

    <pre><code>
        Here is some fun code!
        More code
          One tab
            One more tab
            
            Two tabs and an extra newline character precede me
    </code></pre>
</body>

查询1

CREATE TABLE `database`
    (`sku` varchar(2), `date` datetime)
;

INSERT INTO `database`
    (`sku`, `date`)
VALUES
    ('A1', '2015-01-10 00:00:00'),
    ('A2', '2015-01-15 00:00:00'),
    ('A1', '2015-01-20 00:00:00'),
    ('A1', '2015-02-10 00:00:00'),
    ('A2', '2015-02-10 00:00:00')
;

<强> Results

SELECT sku,
   count(IF(month(date) = 1, sku, null)) AS JAN,
   count(IF(month(date) = 2, sku, null)) AS Feb
FROM `database`
GROUP BY sku