客户在一年内对前50名客户进行多年销售的SQL查询

时间:2015-03-05 19:27:47

标签: sql sql-server select nested

我在SQL服务器中有一个查询,它通过销售成功返回给定年份的前50位客户。我希望扩展它,以便在可能会或可能不会进入前50名的情况下返回他们的销售额。

SELECT TOP 50 CU.CustomerName, SUM(ART.SalesAnalysis) AS '2011'
FROM ARTransaction AS ART, Customer AS CU
WHERE ART.CustomerN = CU.CustomerN AND ART.PostingDate BETWEEN '2010-12-31' AND '2012-01-01'
GROUP By CU.CustomerName
ORDER BY SUM(ART.SalesAnalysis) DESC

我尝试添加嵌套的SELECT语句,但是它们返回了奇怪的结果,我不知道为什么(可能无法工作,但结果让我大吃一惊)。包含时,每行的值都会更改,并且客户会重复。

(SELECT SUM(ART.SalesAnalysis)
WHERE ART.PostingDate BETWEEN '2011-12-31' AND '2013-01-01') AS '2012'

我试图在HAVING的嵌套SELECT中放置一个TOP语句,但这告诉我

" Msg 8114,Level 16,State 5,Line 1

将数据类型varchar转换为数字时出错。"

SELECT CU.CustomerName, SUM(ART.SalesAnalysis) AS '2011'
FROM ARTransaction AS ART 
JOIN Customer AS CU ON ART.CustomerN = CU.CustomerN
GROUP BY CU.CustomerNAme
HAVING CU.CustomerNAme IN 
        (SELECT TOP 50 CU.CustomerName
        FROM ARTransaction
        JOIN Customer ON ARTransaction.CustomerN = Customer.CustomerN
        WHERE ARTransaction.SalesAnalysis BETWEEN '2010-12-31' AND '2012-01-01'
    GROUP BY Customer.CustomerN
    ORDER BY SUM(ART.SalesAnalysis) DESC)

2 个答案:

答案 0 :(得分:0)

你可以使用下面的内容...你会看到你想看的所有年份的所有数据,然后只是获得2011年的前50名

SELECT TOP 50 
    CU.CustomerName, 
    SUM(case when year(ART.PostingDate) = 2011 -- or you could use case when ART.PostingDate BETWEEN '2011-01-01' AND '2011-12-31'
        then ART.SalesAnalysis
        else 0 end) AS 2011, 
    SUM(case when year(ART.PostingDate) = 2012
        then ART.SalesAnalysis
        else 0 end) AS 2012
FROM 
    ARTransaction ART, 
    inner join Customer CU
        on ART.CustomerN = CU.CustomerN
WHERE ART.PostingDate BETWEEN '2011-01-01 AND '2012-12-31'
GROUP By CU.CustomerName
ORDER BY  
    SUM(case when year(ART.PostingDate) = 2011
        then ART.SalesAnalysis
        else 0 end)  DESC

答案 1 :(得分:0)

如果我理解正确,您正在根据2011年的数据寻找前50名客户的销售额 - 并且希望查看2011年前50名的所有年份数据,无论这些客户是否在其他年份进入前50名。

试试这个,它可能需要稍微调整,因为我不知道架构,但如果我正确理解这个问题,这应该可以解决问题。

    WITH Top50 AS (
    SELECT TOP 50 
           CU.CustomerN
          ,SUM(ART.SalesAnalysis) AS SalesTotal
      FROM 
           ARTransaction art
     INNER JOIN
           Customer cu
        ON cu.CustomerN = art.CustomerN
     WHERE 
           ART.PostingDate BETWEEN CAST('2011-01-01' AS DATETIME) 
       AND CAST('2011-12-31' AS DATETIME)
     GROUP BY 
           CU.CustomerN
     ORDER BY 
           SUM(ART.SalesAnalysis) DESC)

    SELECT 
           c.CustomerName
          ,SUM(a.SalesAnalysis) AS TotalSales
          ,YEAR(a.PostingDate) AS PostingDateYear
      FROM
           ARTransaction a
     INNER JOIN
           Customer c
        ON c.CustomerN = a.CustomerN
     INNER JOIN
           Top50 t
        ON t.CustomerN = a.CustomerN
     GROUP BY 
           c.CustomerName
          ,YEAR(a.PostingDate)
     ORDER BY
           PostingDateYear