SQL - 如果没有结果则显示0

时间:2014-04-03 11:19:23

标签: sql-server-2008

我的表格结果如下:

C_Date    C_Time     Day        L_TID     Terminal_Name      Branch   Branch_Name           L_UID     C_Name            C_Unique    L_Result    C_Card
20140327  905        Thursday   4640601   046406 Virdi 4000  46406    Sr Blue Downs 046406  1220578   Tsutsu;Simamkele  1220578     0

正在发生的事情是,如果分支机构没有信息,它根本就不会出现。我想要的是它尽可能显示0。 我已经尝试在C_Date列上做一个CASE,但是所有内容都只是以未知方式显示,但仍未启动我的分支!

以下是我的剧本:

    SELECT 

 tEnter.C_Date, tEnter.C_Time, 
 datename (dw,tEnter.C_Date) AS [Day], 
CONVERT(CHAR(8), GETDATE () -7, 112) as [startdate],
CONVERT(CHAR(8), GETDATE () -1, 112) as [enddate], 
            tEnter.L_TID, 
            tTerminal.C_Name AS Terminal_Name, 
            tTerminal.C_Office AS Branch, 
            tTerminal.C_Place AS Branch_Name, 
            tEnter.L_UID, 
        tEnter.C_Name, 
        tEnter.C_Unique,
        tEnter.L_Result, 
        tEnter.C_Card,
   CASE tEnter.C_Date
        WHEN 1 THEN '1' WHEN 0 THEN 'Nothing' ELSE 'Unknown' END AS 'Test'

INTO #TEMPTABLE

FROM         tEnter INNER JOIN
                      tTerminal ON tEnter.L_TID = tTerminal.L_ID

WHERE 

         tEnter.C_Date between CONVERT(CHAR(8), GETDATE () -7, 112) and 
         CONVERT(CHAR(8), GETDATE () -1, 112)

select * from #TEMPTABLE

2 个答案:

答案 0 :(得分:2)

经过大量的游戏,这就成了伎俩。

        SELECT DISTINCT C_Office
        INTO #Branch
        FROM tTerminal

        SELECT 

        ISNULL(tEnter.C_Date,0) AS C_Date,
        ISNULL( tEnter.C_Time,0) AS C_Time, 
        datename (dw,tEnter.C_Date) AS [Day], 
        CONVERT(CHAR(8), GETDATE () -7, 112) as [startdate],
        CONVERT(CHAR(8), GETDATE () -1, 112) as [enddate], 
                    tEnter.L_TID, 
                    tTerminal.C_Name AS Terminal_Name, 
                    BRN.C_Office AS Branch, 
                    tTerminal.C_Place AS Branch_Name, 
                    tEnter.L_UID, 
                tEnter.C_Name, 
                tEnter.C_Unique,
                tEnter.L_Result, 
                tEnter.C_Card

        INTO #TEMPTABLE2 
        FROM #Branch as BRN

                LEFT OUTER JOIN tEnter 
                on tEnter.C_Office = BRN.C_Office
                AND (tEnter.C_Date between CONVERT(CHAR(8), GETDATE () -7, 112) and CONVERT(CHAR(8), GETDATE () -1, 112))

                LEFT OUTER JOIN tTerminal 
                ON tEnter.L_TID = tTerminal.L_ID

答案 1 :(得分:0)

您需要执行Right Outer Join。我还认为您可能需要将此Where子句移动到Join条件中。由于外部联接,tEnter字段可能为null,但是当您将它们添加到where条件时,您无意中删除了所有没有日期的行(您的行为空)。

  INTO #TEMPTABLE
  FROM         tEnter RIGHT OUTER JOIN
                  tTerminal ON tEnter.L_TID = tTerminal.L_ID
  AND
     tEnter.C_Date between CONVERT(CHAR(8), GETDATE () -7, 112) and 
     CONVERT(CHAR(8), GETDATE () -1, 112)ckquote