2012-11-13 66 views
-1

我建立一個報告,輸出應該是這樣的(例如):SELECT(?=計SUM)與ASP

['11/2012', 5, 2, 0] 
['10/2012', 7, 1, 0] 
['09/2012', 2, 3, 0] 
['08/2012', 0, 0, 1] 
['07/2012', 0, 2, 1] 
['06/2012', 2, 1, 0] 
['05/2012', 3, 1, 1] 
['04/2012', 2, 2, 1] 
['03/2012', 5, 0, 0] 
['02/2012', 7, 1, 0] 
['01/2012', 2, 0, 0] 
['12/2011', 3, 0, 1] 

月內的一部分,我需要得到實際的月份,比列表中的一個一年前。

<% 
    DataAtual_PeriodoInicial= Now 
    DataFinal_PeriodoInicial= DateAdd("m", -13, Now) 
    DO WHILE Datediff("m", DataAtual_PeriodoInicial, DataFinal_PeriodoInicial) <> 0 
%> 
    ['<% Response.Write(Right("0" & Month(DataAtual_PeriodoInicial), 2)) %>/<% Response.Write(Year(DataAtual_PeriodoInicial)) %>', X, Y, Z]<br> 
<% 
    DataAtual_PeriodoInicial= DateAdd("m", -1, DataAtual_PeriodoInicial) 
    LOOP 
%> 

所以這是產生:我有這個代碼做這個

['11/2012', X, Y, Z] 
['10/2012', X, Y, Z] 
['09/2012', X, Y, Z] 
['08/2012', X, Y, Z] 
['07/2012', X, Y, Z] 
['06/2012', X, Y, Z] 
['05/2012', X, Y, Z] 
['04/2012', X, Y, Z] 
['03/2012', X, Y, Z] 
['02/2012', X, Y, Z] 
['01/2012', X, Y, Z] 
['12/2011', X, Y, Z] 

現在我不得不放棄一些數字,而不是X,Y和Z.我有一個表像數據:

11 2012 X 
10 2012 X 
10 2012 X 
10 2012 X 
10 2012 Y 
10 2012 Y 
10 2012 Z 
10 2012 Z 
10 2012 Z 
9 2012 X 
9 2012 X 
9 2012 X 
9 2012 Y 
9 2012 Z 
9 2012 Z 
8 2012 X 
8 2012 X 
8 2012 Y 
8 2012 Y 
8 2012 Y 
8 2012 Y 
8 2012 Y 
... 

我開始與這個選擇:

SELECT 
    datepart(month,SentDate) AS Mes, 
    datepart(year,SentDate) AS Ano, 
    EventType 
FROM 
    SomeTable 
ORDER BY 
    SentDate DESC 

我嘗試了一些組,但沒有成功。我需要某種計數嗎?和?我該如何完成這個問題的頂部輸出?

謝謝!

+0

您標記爲多層薄gs'X',多個事物'Y'和多個事物'Z'。你沒有把列名放在你的表中。您的SQL不適用於您提供的示例數據。 – Laurence

+0

這只是一個例子來解釋我的需求。加比明白了一下。 – Khrys

回答

2

嘗試http://sqlfiddle.com/#!3/93a11/23/0


SELECT 
    datepart(month,SentDate) AS Mes, 
    datepart(year,SentDate) AS Ano, 
    sum(CASE WHEN EventType = 'X' THEN 1 ELSE 0 END) X, 
    sum(CASE WHEN EventType = 'Y' THEN 1 ELSE 0 END) Y, 
    sum(CASE WHEN EventType = 'Z' THEN 1 ELSE 0 END) Z 
FROM 
    SomeTable 
GROUP BY 
    datepart(month,SentDate), 
    datepart(year,SentDate) 
ORDER BY 
    Ano DESC, 
    Mes DESC 
    SentDate DESC 

演示您也可以使用數據透視表

SELECT * FROM 
    (
    SELECT 
    datepart(month,SentDate) AS Mes, 
    datepart(year,SentDate) AS Ano, 
    EventType 
    FROM 
    SomeTable 
) grouped 
PIVOT (COUNT(eventType) for EventType in ([X],[Y],[Z])) AS pivoted 
ORDER BY 
    Ano DESC, 
    Mes DESC 

演示在http://sqlfiddle.com/#!3/93a11/16/0

+0

由於語法錯誤而更新... –

+0

不錯!謝謝您的幫助。祝你有個美好的一天=) – Khrys