可以从SQL中的一个空临时表中选择导致结果为空吗?

时间:2010-07-15 17:32:21

标签: sql sql-server-2005 temp-tables

这是我的问题。我正在创建4个临时表来计算特定类型的盒子和员工的工作时间。给定开始日期和结束日期,我们想知道每种类型(1,2和3)的总箱数以及它们在该时间段内的总工作时数。如果每种类型中至少有一种类型,则所有方法都可以正常工作,但如果只存在两种类型,那么我将得到整个最终SELECT语句的空白结果。

那么,在FROM行中包含空临时表的SELECT语句是否会导致其他所有内容返回空白?

例如,日期范围6-1-10到6-10-10返回10个类型1框,12个类型2框,0个类型3框和36小时,但显示的结果为空白。但如果它延长了一天,并且包含了15个类型3的框,则查询可以正常工作。

SELECT Count(isnull(Box_Num,0)) as Box1, emp_num INTO #Box1
FROM  TEST.dbo.Prod_beta2
WHERE BoxType like '1' and time  > '06/01/10' + ' 12:01 AM'  and time  < '06/10/10' + ' 11:59pm' and emp_num like '10467'
group by emp_num


SELECT Count(isnull(Box_Num,0)) as Box2, emp_num INTO #Box2
FROM TEST.dbo.Prod_beta2
WHERE BoxType like '2' and time > '06/01/10' + ' 12:01 AM' and time < '06/10/10' + ' 11:59pm' and emp_num like '10467'
group by emp_num


SELECT count(isnull(box_num,0)) as Box3, emp_num INTO #Box3
from TEST.dbo.Prod_beta2
WHERE BoxType like '3' and time > '06/01/10' + '  12:01 AM' and time < '06/10/10' + ' 11:59pm' and emp_num like '10467'
group by emp_num


SELECT SUM(HOURS) as TotalHours, empid INTO #Hours
FROM TEST.dbo.Timeclock
where timein > '06/01/10' + ' 12:01 AM' and timein < '06/10/10' + ' 11:59pm' and empid like '10467'
group by empid


SELECT Box1, Box2, Box3, TotalHours
FROM #Box1, #Box2, #Box3, #Hours


DROP TABLE #Box1, #Box2, #Box3, #Hours

2 个答案:

答案 0 :(得分:2)

是。您正在做笛卡尔积,这意味着您将在结果中包含B1 * B2 * B3 * H行。

当B3没有行时,你显然会乘以零。

前三个条件可以轻松组合(顺便说一下BoxTypeemp_num的数据类型是什么?如果它们是数字,那么不要使用字符串来避免任何不必要的类型转换问题。此外,您的日期逻辑似乎在11:59 pm到12:01 AM之间遗漏了任何内容。这是故意吗?此外,如果您更换服务器等,您应该使用ISO日期格式以避免任何问题。)

SELECT 
Count(CASE WHEN BoxType = '1' THEN 1 ELSE NULL END) as Box1,
 Count(CASE WHEN BoxType = '2' THEN 1 ELSE NULL END) as Box2,
 Count(CASE WHEN BoxType = '3' THEN 1 ELSE NULL END) as Box3
FROM  TEST.dbo.Prod_beta2
WHERE BoxType in ('1','2','3') and time  > '06/01/10' + ' 12:01 AM'  and 
  time  < '06/10/10' + ' 11:59pm' and emp_num like '10467'
group by emp_num

答案 1 :(得分:0)

如果字段都是相同的类型,那么你不应该这样做:

SELECT Box1, Box2, Box3, TotalHours 
FROM #Box1, #Box2, #Box3, #Hours

您应该使用UNION ALL查询

像这样:

   SELECT Count(isnull(Box_Num,0)) as Box1, emp_num
    FROM  TEST.dbo.Prod_beta2 
    WHERE BoxType like '1' and time  > '06/01/10' + ' 12:01 AM'  and time  < '06/10/10' + ' 11:59pm' and emp_num like '10467' 
    UNION ALL
    SELECT Count(isnull(Box_Num,0)) as Box2, emp_num
    FROM TEST.dbo.Prod_beta2 
    WHERE BoxType like '2' and time > '06/01/10' + ' 12:01 AM' and time < '06/10/10' + ' 11:59pm' and emp_num like '10467' 
    UNION ALL

SELECT count(isnull(box_num,0)) as Box3, emp_num
from TEST.dbo.Prod_beta2
WHERE BoxType like '3' and time > '06/01/10' + '  12:01 AM' and time < '06/10/10' + ' 11:59pm' and emp_num like '10467'
group by emp_num

您的上一次选择是唯一不同的,所以只是将查询与显示的框数分开。

但是,你甚至不需要临时表,只需使用标准的SELECT语句,并为每个语句添加union all。

如果其中任何一个查询包含0行,则当前语句将产生0行。 Look into cartesian products and what they mean