sql当我使用group by时,我不想丢失空值

时间:2014-10-17 20:43:49

标签: sql sql-server null group-by

我正试图找到哪个merch访问了他的路线之外的poi。为了做到这一点,我需要从vp.poiid中找到空值,但是当我创建组时,我在该列上丢失了空值。

.
.
.
(SELECT
    vp.routedate AS Date,
    me.MerchName,
    me.id AS Merchid,
    ov.poiid AS Done,
    vp.poiid AS Planned,
    CASE WHEN ov.poiid IS NULL THEN COUNT(ov.poiid) END AS notDone,
    CASE WHEN vp.poiid IS NULL THEN COUNT(vp.poiid) END AS outOfRoute

FROM atb_visitplan vp

FULL JOIN OutVisitData ov ON (vp.poiid = ov.poiid 
AND ov.commitdate = vp.routedate 
AND vp.merchid = ov.merchid)

INNER JOIN atb_merchs me ON (vp.merchid = me.id)

WHERE me.id = 1  
GROUP BY 
    vp.routedate,
    me.MerchAd,
    me.id,
    ov.poiid,
    vp.poiid
) a
.
.
.

当我运行这个子查询时,我得到了这个观点:

     date                 name      id  done   planned  notdone  outofroute
2013-11-06 00:00:00.000 Seven Kavak 1   30      30      0       NULL
2013-11-06 00:00:00.000 Seven Kavak 1   34      34      0       NULL
2013-11-06 00:00:00.000 Seven Kavak 1   48      48      0       NULL
2013-11-06 00:00:00.000 Seven Kavak 1   54      54      0       NULL
2013-11-06 00:00:00.000 Seven Kavak 1   NULL    1235    1235    NULL
2013-11-06 00:00:00.000 Seven Kavak 1   NULL    1236    1236    NULL
2013-11-07 00:00:00.000 Seven Kavak 1   30      30      0       NULL
2013-11-07 00:00:00.000 Seven Kavak 1   49      49      0       NULL

正如您在此结果中看到的,outOfRoute将所有值都设为NULL(但实际上并非如此)。有没有办法在这张表中看到实际结果?我需要对这些列进行分组,这是一个子查询,我计算最终结果。计划列实际上有空值,但我也看不到它们。

PS:我正在使用sql server

2 个答案:

答案 0 :(得分:0)

我想我第一次误读了。你想要计算那些有空值的记录,对吧?

COUNT(SELECT * FROM ov WHERE ov.poiid IS NULL) AS notDone,
COUNT(SELECT * FROM vp WHERE vp.poiid IS NULL) AS outOfRoute

您当前的陈述说,"当分组字段为空时显示这些记录的计数,"它看起来永远不会。

您需要在这些选择中重新定义连接;我暂时走的很简短。

(改写,我希望,更好的回答。)

答案 1 :(得分:0)

只有当vp.poiid为空并且您没有其他部分时,您的CASE WHEN vp.poiid IS NULL THEN COUNT(vp.poiid) END AS outOfRoute语句才会计算。如果我检查结果,那么vp.poiid AS Planned列的所有值都显示为outOfRoute column,那么您将获得空值。