Microsoft SQL:当值不存在时,在结果中包含虚拟行

时间:2016-04-04 20:42:44

标签: sql sql-server

我正在为每个国家退回一段时间的总销售额。有时一个国家不会出现在结果中,因为他们在那段时间内没有任何订单。对于没有销售的这些国家/地区,我希望在结果中包含国家/地区缩写名称和销售总额,其值为“0”。例如,NL和IS也应包含在结果中,Sales_Total的值均为“0”。当该国在此期间没有任何销售时,我如何在结果中包含那些假人行?

**QUERY:**

SELECT 
    Country,
    SUM(TOTAL) AS Sales_Total   
FROM Orders
WHERE OrderDate BETWEEN '2014-01-01' AND '2014-12-31'
GROUP BY Country


**RESULTS**

Country   Total_Sales
AU        7646
CA        13773
KR        13976
NZ        1831
US        69421


**Required Results:**

Country   Total_Sales
AU        7646
CA        13773
KR        13976
NZ        1831
US        69421
NL        0
IS        0

4 个答案:

答案 0 :(得分:3)

这应该这样做:

  SELECT     Country
            , Sales_Total=ISNULL(Sales_Total,0)
    FROM
             (SELECT o.Country
                  , SUM(TOTAL) AS Sales_Total
              FROM   Orders
              WHERE  OrderDate BETWEEN '2014-01-01' AND '2014-12-31'
              GROUP BY Country) AS o
             RIGHT OUTER JOIN
                          (SELECT DISTINCT
                                Country
                           FROM   Orders) AS C ON o.Country = c.Country;

答案 1 :(得分:2)

我会使用(如果需要的话创建)可以从外部加入的国家/地区表。然后你可以这样写;

SELECT 
    c.CountryCode,
    SUM(TOTAL) AS Sales_Total   
FROM Country c
LEFT JOIN Orders o
    in c.CountryCode = o.Country AND o.OrderDate BETWEEN '2014-01-01' AND '2014-12-31'
GROUP BY c.CountryCode

答案 2 :(得分:1)

Giorgos有一种方法,但您也可以将查询加入到另一个表(或同一个表)中的国家/地区列表中。像这样:

SELECT c.Country, ISNULL(s.Sales_Total,0) FROM 
    Countries AS c LEFT JOIN 
    (SELECT 
        Country,
        SUM(TOTAL) AS Sales_Total   
    FROM Orders
    WHERE OrderDate BETWEEN '2014-01-01' AND '2014-12-31'
    GROUP BY Country) s 
    ON c.Country = s.Country

答案 3 :(得分:-1)

您可以将WHERE子句的谓词放在SUM

SELECT 
    Country,
    SUM(CASE WHEN OrderDate BETWEEN '2014-01-01' AND '2014-12-31' 
               THEN TOTAL 
             ELSE 0
        END) AS Sales_Total   
FROM Orders
GROUP BY Country