使用ASP进行SELECT(Count?SUM?)

时间:2012-11-13 14:00:18

标签: sql asp-classic

我正在构建一个报告,输出应该像(例子):

['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

我试过了一些小组,但没有过了。我需要某种伯爵吗?和?我怎样才能完成这个问题顶部的输出?

谢谢!

1 个答案:

答案 0 :(得分:2)

试试这个

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

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

演示

您也可以使用PIVOT表

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

演示