SQL Server填充空值或不存在值

时间:2015-10-15 08:13:46

标签: sql-server

我在SQL Server中有两个表:

表一

int array[] = {0, 1, 2, 3};

表二

int array[4] = {0, 1, 2, 3};

我想写一个计算dept数量的查询,如果dept不在表1中,它应该返回0。

至于上表1中的例子。缺少第7和第8部分,但我希望将其包含在我的最终结果中,看起来如下表所示。

请帮助

table sample here

Weeknumber  Dept        
    1       Sales
    1       Sales
    1       Sales
    2       Transport
    3       Call centre
    4       Sales
    5       Personel
    6       Marketing       
    9       HR
    9       HR
    10      Purchases

2 个答案:

答案 0 :(得分:2)

您只需要使用带有COUNT的子查询:

SELECT t2.Weeknumber, 
       Count_OF_Dept = (SELECT COUNT(*) FROM TableOne t1
                        WHERE t1.Weeknumber = t2.Weeknumber)
FROM TableTwo t2

您的样本:http://sqlfiddle.com/#!6/ab62b/1/0

答案 1 :(得分:1)

试试这样。只需将其粘贴到一个空的查询窗口中即可执行。

注意:有一个非常漂亮的功能来创建一组正在运行的数字,这些数字将在开头创建并在最后删除。如果您确定,只删除数据库中没有此名称的函数!

如果您不想创建新功能,请告诉我,我会帮助您将其替换为"在运行中"通过CTE解决方案。

CREATE FUNCTION [dbo].[RunningNumbers](@counter INT=1000000, @StartAt INT=0)
RETURNS TABLE
AS 
RETURN
    WITH E1(N) AS(SELECT 1 FROM(VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))t(N)), --10 ^ 1
    E2(N) AS(SELECT 1 FROM E1 a CROSS JOIN E1 b), -- 10 ^ 2 = 100 rows
    E4(N) AS(SELECT 1 FROM E2 a CROSS JOIN E2 b), -- 10 ^ 4 = 10,000 rows
    E8(N) AS(SELECT 1 FROM E4 a CROSS JOIN E4 b), -- 10 ^ 8 = 10,000,000 rows
    CteTally AS
    (
        SELECT TOP(ISNULL(@counter,1000000)) ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) -1 + ISNULL(@StartAt,0) As Nmbr
        FROM E8
    )
    SELECT * FROM CteTally;

GO

DECLARE @tbl TABLE(WeekNumber INT,Dept VARCHAR(100));
INSERT INTO @tbl VALUES
 (1,'Sales')
,(1,'Sales')
,(1,'Sales')
,(2,'Transport')
,(3,'Call centre')
,(4,'Sales')
,(5,'Personel')
,(6,'Marketing')   
,(9,'HR')
,(9,'HR')
,(10,'Purchases');

SELECT weekNmbrs.Nmbr
      ,Tbl.WeekNumber
      ,COUNT(Tbl.Dept)
FROM dbo.RunningNumbers(10,1) AS weekNmbrs 
LEFT JOIN @tbl AS Tbl ON weekNmbrs.Nmbr=Tbl.WeekNumber 
GROUP BY weekNmbrs.Nmbr, Tbl.WeekNumber
ORDER BY weekNmbrs.Nmbr ;

--Clean up
/* Are you sure?
DROP FUNCTION dbo.RunningNumbers; 
*/