0

我大家,尽管阅读了许多文档和网页,但我不知道如何使我的代码工作。

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 吗?但是如何?

4

2 回答 2

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
于 2013-02-06T18:29:56.163 回答
0

您可以使用以下内容来透视数据:

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
于 2013-02-06T18:42:11.620 回答