SQL中的条件计数返回

时间:2018-03-09 18:17:20

标签: sql conditional

我看过这些示例,我认为我应该使用JOIN,但我无法正确使用语法,这只是错误。我需要退一张桌子 根据标准显示计数。

我的程序看起来像这样

SELECT  SalesMan, Count(SalesMan) AS SalesCount 
FROM  Customers
WHERE SaleDate Between @BeginDate And @EndDate AND Status = 'SOLD' 
GROUP BY SalesMan 
ORDER BY SalesCount DESC  

SELECT DISTINCT SalesMan2, Count(Salesman2)   AS HalfCount  
FROM  Customers
WHERE SaleDate   Between @BeginDate And @EndDate AND Status = 'SOLD'   
GROUP BY SalesMan2   
ORDER BY HalfCount DESC

返回两个看起来像这样的表

SalesMan | SalesCount

BOB        8
ANDY       5
JOE        3

SalesMan2 | HalfCount

(blank)    40
ANDY       1
JACOB      1
ROB        1
JOE        1

我正在努力工作的逻辑是..如果他们是推销员加1,如果他们是Salesman2然后添加.5。另外,我在第二张表中得到了一堆我不在乎的空箱。我不需要那些。

我需要的是它返回

Salesman | SalesCount

BOB       8
ANDY      5.5
JOE       3.5
JACOB     .5
ROB       .5

我看了很多答案,但是他们使用了JOins和where子句和字符串。他们也知道他们应该匹配的价值。 任何指导我正确方向的帮助将不胜感激。 提前谢谢。

3 个答案:

答案 0 :(得分:1)

数据库未规范化,这将使此查询更难以实现。虽然坚持这个结构,但这是我要开始的地方:

SELECT
    COALESCE(NULLIF(SalesMan, ''), NULLIF(SalesMan2, '')),
    SUM(CASE WHEN COALESCE(SalesMan, '') <> '' THEN 1.0 ELSE 0.0 END) +
        SUM(CASE WHEN COALESCE(SalesMan2, '') <> '' THEN 0.5 ELSE 0.0 END) AS SalesCount
FROM Customers C1
FULL OUTER JOIN Customers C2 ON
    C2.SalesMan = C1.SalesMan2 AND
    C2.Status = 'SOLD' AND
    C2.SaleDate BETWEEN @BeginDate AND @EndDate
WHERE
    C1.Status = 'SOLD' AND
    C1.SaleDate BETWEEN @BeginDate AND @EndDate
GROUP BY
    COALESCE(NULLIF(SalesMan, ''), NULLIF(SalesMan2, ''))

由于您没有包含设置测试方案的代码,因此这是未经测试的,并且是我的头脑。如果没有给出正确的结果,请告诉我。

答案 1 :(得分:1)

一种方法使用union all

SELECT SalesMan, SUM(cnt) AS SalesCount 
FROM  ((select c.SalesMan, 1 as cnt
        FROM Customers c
        WHERE SaleDate Between @BeginDate And @EndDate AND Status = 'SOLD' 
       ) UNION ALL
      (SELECT SalesMan2, 0.5 as cnt
       FROM Customers c
       WHERE SaleDate Between @BeginDate And @EndDate AND Status = 'SOLD'
      )
     ) c
GROUP BY SalesMan;

答案 2 :(得分:0)

我真的很感激帮助。我尝试了两种解决方案,戈登的解决方案开箱即用。

有效的程序如下

SELECT SalesMan, SUM(cnt) AS SalesCount 
FROM  ((select c.SalesMan, 1 as cnt
FROM Customers c
    WHERE SaleDate Between @BeginDate And @EndDate AND Status = 'SOLD' 
   ) UNION ALL
  (SELECT SalesMan2, 0.5 as cnt
   FROM Customers c
   WHERE SaleDate Between @BeginDate And @EndDate AND Status = 'SOLD' AND 
   SalesMan2 <> ''
  )
 ) c
GROUP BY SalesMan ORDER BY SalesCount DESC ;   

我添加了AND SalesMan2&lt;&gt; &#39;&#39;和Order By子句一起工作完美。

我也在使用MSSQL。我记得将来发布这个帖子。