SQL如果一个月的表中没有数据,如何显示一个月的“0”值

时间:2012-05-02 14:50:20

标签: sql-server sql-server-2005

首先,我的结果如下:
  | KONTONR |月| SELSKAPSKODE | BELOP |
 | 459611 ---- | 1 ------ | BAGA -------------- | 156000 |
| 459611 ---- | 2 ------ | BAGA -------------- | 73000 - |
| 459611 ---- | 4 ------ | BAGA --------------- | 217000- |
| 459611 ---- | 5 ------ | BAGA --------------- | 136000- |
| 459611 ---- | 1 ------- | CIVO --------------- | 45896 - |
| 459611 ---- | 3 ------ | CIVO ---------------- | 32498 - |
| 459611 ---- | 4 ------ | CIVO ---------------- | 9841 --- |
| 330096 ---- | 1 ------ | BAGA --------------- | 42347 - |
| 330096 --- | 3 ------- | BAGA --------------- | 3695 --- |
|等等。

我试图在几个帐户上显示月份2个月的预订,每个帐户(KONTONR)有几个代码(SELSKAPSKODE),其中记录了预订(预订的总和为BELOP)。我想概述一下每个帐户(SELSKAPSKODE)每个帐户(KONTONR)的预订总额(BELOP)。我的问题是,如果没有对该代码进行预订,则代码在一个月内不会显示。有没有办法来解决这个问题?我理解为什么代码没有显示,因为它们根本就不在我正在查询的表中。而且我怀疑sollution正在制作一个'假'表,然后我加入(左外连接?)和'另一个'表。
我只是无法让它工作,我对SQL很新...有人可以帮忙吗? 我的查询看起来像这样(我只插入'嵌套'查询来为连接设置,如果这样做了吗?!):

SELECT        TOP (100) PERCENT KONTONR, Month, SELSKAPSKODE, BELOP  
FROM            (SELECT        SELSKAPSKODE, KONTONR, SKIPS_KODE, MONTH(POSTDATO) AS  
Month, SUM(BELOP) AS BELOP  
FROM            dbo.T99_DETALJ  
WHERE        (POSTDATO >= '2012-01-01') AND (BILAGSART = 0 OR BILAGSART = 2)                       
GROUP BY SELSKAPSKODE, KONTONR, SKIPS_KODE, MONTH(POSTDATO)) AS T99_summary  
GROUP BY KONTONR, SELSKAPSKODE, Month, BELOP  
ORDER BY KONTONR, SELSKAPSKODE, Month  

总而言之,我想“填补”缺失的月份(参见开头的表格),例如账户(KONTONR)459611第3个月“缺少”。我想展示第3个月,预订总和(BELOP)为'0'。非常感谢任何帮助,提前谢谢!

3 个答案:

答案 0 :(得分:3)

您可以使用值1-12查询表格,并在左外部加入您的结果。

以下是使用表变量而不是查询的示例,以及使用CTE构建带数字的表的示例。

declare @T table
(
  Month int
)

insert into @T values(1)
insert into @T values(1)
insert into @T values(1)
insert into @T values(3)
insert into @T values(3)

;with Months(Month) as
(
  select 1
  union all
  select Month + 1
  from Months
  where Month < 12
)
select M.Month,
       count(T.Month) Count,
       isnull(sum(T.Month), 0) Sum
from Months as M
  left outer join @T as T
    on M.Month = T.Month
group by M.Month

结果:

Month       Count       Sum
----------- ----------- -----------
1           3           3
2           0           0
3           2           6
4           0           0
5           0           0
6           0           0
7           0           0
8           0           0
9           0           0
10          0           0
11          0           0
12          0           0

答案 1 :(得分:0)

如果你不想做所有这些,你也可以修改它:SUM(BELOP)用这个: 总和(BELOP不为空的情况,然后是1,否则为0)

答案 2 :(得分:0)

如果您要计算的互动有一个创建日期,那么您也可以添加年份,如果您的互动跨越了多年的时间,这可能会有所帮助。

with Months(Month) as
(
  select 1
  union all
  select Month + 1
  from Months
  where Month < 12
)
select M.Month, year(CreatedOn) as Year,
       count(amount) Count,
       isnull(sum(amount), 0) Sum
from Months as M
  left outer join Charge as C
    on M.Month = (month(CreatedOn))
group by M.Month, year(CreatedOn) order by year(CreatedOn)

output