我是大家,尽管阅读了很多文档和网页,但我还是得不到如何使我的代码工作。
select
(select count(*) from toto where (ddate between '2012-01-01' and '2012-12-31') group by produit) "2012",
(select count(*) from toto where (ddate between '2011-01-01' and '2011-12-31') group by produit) '2011',
(select count(*) from toto where (ddate between '2010-01-01' and '2010-12-31') group by produit) '2010'
我有一个SQL错误代码:1242消息。是的,这是正常的,因为我确实有超过1行要返回。
我该怎么处理?使用PIVOT?但是如何?
答案 0 :(得分:1)
试试这个;
select produit,
sum(case when ddate between '2012-01-01' and '2012-12-31' then 1 else 0 end) as '2012',
sum(case when ddate between '2011-01-01' and '2011-12-31' then 1 else 0 end) as '2011',
sum(case when ddate between '2010-01-01' and '2010-12-31' then 1 else 0 end) as '2010'
from toto
where ddate between '2010-01-01' and '2012-12-31'
group by produit
答案 1 :(得分:0)
您可以使用以下内容 pivot 数据:
select produit,
COUNT(case when ddate = '2012' then produit end) as Year_2012,
COUNT(case when ddate = '2011' then produit end) as Year_2011,
COUNT(case when ddate = '2010' then produit end) as Year_2010
from
(
select produit,
year(ddate) ddate
from toto
where ddate between '2010-01-01' and '2012-12-31'
) src
group by produit