昨天做了一个统计页面。
要求很简单,按父表——旅馆表[MOBILE_HY]分组统计子表——上传信息表[MOBILE_LSXX]上每个旅店一段日期(格式YYYY-MM-DD)内上传的信息数。
表结构如下:
其中主要的就是[MOBILE_LSXX].HYID 对应于[MOBILE_HY].ID。即旅馆编号。
[MOBILE_LSXX].SCSJ,是时间,根据它筛选一段时间。
[MOBILE_LSXX]其他字段不需要考虑反正就是统计记录个数。我用[MOBILE_LSXX].ID字段统计。
开始我认为很容易:
SELECT dbo.MOBILE_HY.[HYMC] as mc,count([dbo].[MOBILE_LSXX].[id]) as sl,dbo.MOBILE_HY.ID as hyid
FROM dbo.MOBILE_HY left JOIN
dbo.MOBILE_LSXX ON dbo.MOBILE_HY.ID = dbo.MOBILE_LSXX.HYID
WHERE
[dbo].[MOBILE_LSXX].[SCSJ] between '2009-04-21' and '2009-04-22'
group by dbo.MOBILE_HY.[HYMC] ,dbo.MOBILE_HY.ID
FROM dbo.MOBILE_HY left JOIN
dbo.MOBILE_LSXX ON dbo.MOBILE_HY.ID = dbo.MOBILE_LSXX.HYID
WHERE
[dbo].[MOBILE_LSXX].[SCSJ] between '2009-04-21' and '2009-04-22'
group by dbo.MOBILE_HY.[HYMC] ,dbo.MOBILE_HY.ID
是能够统计,但是由于条件筛选,这期间没有上传的用户的记录小旅店,筛选后的记录里根本没有此小旅店的记录,在分组统计的时候也当然对没有上传记录的小旅店分组(因为记录集里根本没有嘛)。
开始以为是联接错误,还特意改成左联接 。还是无效,后来才想到上面的原因。
在同事的提示下,采用如下办法:先统计有的,再根据父表列出没有的,然后联合。
select * from
(
SELECT dbo.MOBILE_HY.[HYMC] as mc,count([dbo].[MOBILE_LSXX].[id]) as sl,dbo.MOBILE_HY.ID as hyid
FROM dbo.MOBILE_HY left JOIN
dbo.MOBILE_LSXX ON dbo.MOBILE_HY.ID = dbo.MOBILE_LSXX.HYID
WHERE
[dbo].[MOBILE_LSXX].[SCSJ] between '2009-04-21' and '2009-04-22'
group by dbo.MOBILE_HY.[HYMC] ,dbo.MOBILE_HY.ID
union
select dbo.MOBILE_HY.[HYMC] as mc,0 as sl,dbo.MOBILE_HY.[id] as hyid
from dbo.MOBILE_HY
where
dbo.MOBILE_HY.ID not in
(select dbo.MOBILE_LSXX.HYID
from dbo.MOBILE_LSXX
where
[dbo].[MOBILE_LSXX].[SCSJ] between '2009-04-21' and '2009-04-22'
)
) as T
order by hyid
(
SELECT dbo.MOBILE_HY.[HYMC] as mc,count([dbo].[MOBILE_LSXX].[id]) as sl,dbo.MOBILE_HY.ID as hyid
FROM dbo.MOBILE_HY left JOIN
dbo.MOBILE_LSXX ON dbo.MOBILE_HY.ID = dbo.MOBILE_LSXX.HYID
WHERE
[dbo].[MOBILE_LSXX].[SCSJ] between '2009-04-21' and '2009-04-22'
group by dbo.MOBILE_HY.[HYMC] ,dbo.MOBILE_HY.ID
union
select dbo.MOBILE_HY.[HYMC] as mc,0 as sl,dbo.MOBILE_HY.[id] as hyid
from dbo.MOBILE_HY
where
dbo.MOBILE_HY.ID not in
(select dbo.MOBILE_LSXX.HYID
from dbo.MOBILE_LSXX
where
[dbo].[MOBILE_LSXX].[SCSJ] between '2009-04-21' and '2009-04-22'
)
) as T
order by hyid
问题解决