通过编写以下查询
SELECT item_name, YEAR( DATE ) , SUM( item_sold_qty )
FROM item
JOIN sales ON item.id = sales.item_number
GROUP BY YEAR( DATE ) , item_name
ORDER BY item_name
我能够得到以下结果
item_name YEAR( DATE ) SUM( item_sold_qty )
pencil 2011 22
pencil 2012 44
eraser 2012 22
eraser 2011 11
pen 2012 66
pen 2011 33
nib 2012 88
nib 2011 44
相反,我希望以下列方式得到结果
item_name 2011 2012
pencil 22 44
eraser 11 22
pen 33 66
nib 44 88
我对sql并不擅长,也不知道如何将年份设置为列名。 需要帮助。
注意 ::我的数据库有2个表。销售表的日期列具有不同的日期,如2012-03-01,2012-04-02,2011-07-03,依此类推......
答案 0 :(得分:5)
也许是这样的:
SELECT
item_name,
SUM(CASE WHEN YEAR( DATE )=2011 THEN item_sold_qty ELSE 0 END) AS '2011',
SUM(CASE WHEN YEAR( DATE )=2012 THEN item_sold_qty ELSE 0 END) AS '2012'
FROM
item
JOIN sales ON item.id = sales.item_number
GROUP BY
item_name
ORDER BY
item_name
修改强>
如果你想要其他年份并仍然总结它们。然后你可以这样做:
SELECT
item_name,
SUM(CASE WHEN YEAR( DATE )=2011 THEN item_sold_qty ELSE 0 END) AS '2011',
SUM(CASE WHEN YEAR( DATE )=2012 THEN item_sold_qty ELSE 0 END) AS '2012',
SUM(CASE WHEN NOT YEAR( DATE ) IN (2011,2012) THEN item_sold_qty ELSE 0 END) AS 'AllOtherYears'
FROM
item
JOIN sales ON item.id = sales.item_number
GROUP BY
item_name
ORDER BY
item_name
<强> EDIT2 强>
如果你有很多年,而且你不想继续增加岁月。然后你需要使用动态sql。这意味着您连接sql的varchar然后执行它。
有用的参考资料:
答案 1 :(得分:1)
上面的答案可行,但每年增加一个案例可能适用也可能不适合。 如果您使用的是PHP平台,则可以更改现有数组的布局,例如
foreach($items as $item)
{
$item_names[$item[item_name]][$item[year]] += $item[item_sold_qty];
}
这将生成如下数组:
Array
(
[pencil] => Array
(
[2011] => 22
[2012] => 44
)
[eraser] => Array
(
[2012] => 22
[2011] => 11
)
[pen] => Array
(
[2012] => 66
[2011] => 33
)
[nib] => Array
(
[2012] => 88
[2011] => 44
)
)
同时更改原始查询以为变量指定更好的名称:
SELECT item_name, YEAR( DATE ) as year , SUM( item_sold_qty ) as item_sold_qty
FROM item
JOIN sales ON item.id = sales.item_number
GROUP BY YEAR( DATE ) , item_name
ORDER BY item_name
以上假设您的mysql结果数组看起来像这样:
Array
(
[0] => Array
(
[item_name] => pencil
[year] => 2011
[item_sold_qty] => 22
)
[1] => Array
(
[item_name] => pencil
[year] => 2012
[item_sold_qty] => 44
)
[2] => Array
(
[item_name] => eraser
[year] => 2012
[item_sold_qty] => 22
)
[3] => Array
(
[item_name] => eraser
[year] => 2011
[item_sold_qty] => 11
)
[4] => Array
(
[item_name] => pen
[year] => 2012
[item_sold_qty] => 66
)
[5] => Array
(
[item_name] => pen
[year] => 2011
[item_sold_qty] => 33
)
[6] => Array
(
[item_name] => nib
[year] => 2012
[item_sold_qty] => 88
)
[7] => Array
(
[item_name] => nib
[year] => 2011
[item_sold_qty] => 44
)
)
答案 2 :(得分:0)
下面:
SELECT
i.item_name,
SUM(s1.item_sold_qty) AS '2011',
SUM(s2.item_sold_qty) AS '2012'
FROM item i
LEFT JOIN sales s1 ON (i.id = s1.item_number AND YEAR(s1.DATE) = 2011)
LEFT JOIN sales s2 ON (i.id = s2.item_number AND YEAR(s2.DATE) = 2012)
GROUP BY i.item_name
ORDER BY i.item_name
当然,您需要添加任意数量的联接,而不是您想要搜索的多年......