0

我有一张票表。我正在尝试计算在本年度每个月末“开放”的门票数量。同样,我将其推送到条形图,我需要通过 LINQ 将其放入数组中。

我的 SQL 查询得到我的计算是:

SELECT
    (SELECT COUNT(*) FROM tblMaintenanceTicket t WHERE (CreateDate < DATEADD(MM, 1, '01/01/2012')))
    -
    (SELECT COUNT(*) FROM tblMaintenanceTicket t WHERE (CloseDate < DATEADD(MM, 1, '01/01/2012'))) AS 'Open @Month End'

我的逻辑如下:计算在月初和月底之间打开的所有门票。从月底前关闭的票中减去该计数。

更新: 我已经用下面的评论更新了我的查询,但它不适用于 GROUP 中的错误,但我并没有真正理解我猜想的逻辑,我缺乏 SQL 技能是罪魁祸首。

我添加了一个 SQL Fiddle 示例来向您展示我的查询:http ://sqlfiddle.com/#!3/c9b638/1

期望的输出:

-----------
| Jan | 3 |
-----------
| Feb | 4 |
-----------
| Mar | 0 |
-----------
4

2 回答 2

1

Your SQL has several erros . . . are grouping by CreateDate but you don't have it as a column from the subqueries. And, you don't have a column alias on the count(*).

I think this is what you are trying to do:

select DATENAME(MONTH,CreateDate), DATEPART(YEAR,CreateDate),
       (sum(case when CreateDate < DATEADD(MM, 1, '01/01/2012') then 1 else 0 end) -
        sum(case when CloseDate < DATEADD(MM, 1, '01/01/2012') then 1 else 0 end)
       )
from tblMaintenanceTicket
group by DATENAME(MONTH,CreateDate), DATEPART(YEAR,CreateDate)

Your comment seems to elucidate what you want clearer than your question (the explanation in the question is a bit buried). What you need is a driver table of months and then join this to your table. Something like:

select mons.yr, mons.mon, count(*) as OpenTickets
from (select month(CreateDate) as mon, year(CreateDate) as yr,
             cast(min(CreateDate) as date) as MonthStart,
             cast(max(CreateDate) as date) as monthEnd
      from tblMaintenanceTicket
      group by month(CreateDate), year(CreateDate) 
     ) mons left outer join
     tblMaintenanceTicket mt
     on mt.CreateDate <= mons.MonthEnd and
        (mt.CloseDate > mons.MonthEnd or mt.CloseDate is null)
group by mons.yr, mons.mon

I am assuming records are created on every day. This is a convenience so I don't have to think about getting the first and last day of each month using other SQL functions.

于 2012-12-07T18:43:44.433 回答
1

如果您的查询返回您需要的内容,则只需使用DATENAME(MONTH, yourDate)检索月份并按月、年分组:

 SELECT SUM(*), DATENAME(MONTH,yourDate), DATEPART(YEAR,yourDate)
 FROM
 (
     your actual query here
 )
 GROUP BY DATENAME(MONTH,yourDate), DATEPART(YEAR,yourDate)
于 2012-12-07T17:24:09.487 回答