2013-02-06 50 views
0

儘管我閱讀了很多文檔和網頁,但我仍然沒有如何讓代碼工作。SQL錯誤代碼:1242 /如何在表中轉換我的代碼?

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

的數據庫您使用的?無論如何,請將該標籤添加到問題中(例如,mysql,sql-server,oracle等) – Bohemian

回答

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 
+0

現在它很好用。非常感謝卡夫。 –

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 
+1

我很在意子查詢是否是個好主意。它使得案例更簡單,但是通過使批量加倍,損失很小(性能和查詢大小)都會丟失。我預計這將執行大約1/2以及卡夫的查詢。我要與「不是一個好主意」 – Bohemian

+0

@Bohemian我只是想提出一個替代版本的查詢。我的首選是使用'PIVOT'功能,但他們沒有聲明他們正在使用的數據庫。 – Taryn