SQL返回错误的总数

时间:2017-04-11 08:42:45

标签: mysql sql

我有这个数据库:

stock database

我有这个sql :(黑白两种)

SELECT 
    SUM(XS) AS TotalXS 
FROM 
    (SELECT XS 
     FROM `bng` 
     WHERE Color = 'White' 
       AND Action = 'Add' OR Action = 'Transfer Location' 

     UNION ALL 

     SELECT (XS*-1) AS GetXS 
     FROM `bng` 
     WHERE Color = 'White' AND Action = 'Used/ Damaged') AS FinalXS

我的问题是:这个SQL返回错误的总数为" WHITE"只要。见下面的结果:

enter image description here

White的结果应为" 13"对于所有列。我试图找到解决方案,但它们都不适合我。我也想知道我做错了什么。希望你们能帮助我解决这个问题。

2 个答案:

答案 0 :(得分:2)

问题是在第一个子查询中缺少括号和(缺少)运算符优先级:

WHERE Color = 'White' 
    AND Action = 'Add' OR Action = 'Transfer Location' 

您可能希望这是

WHERE Color = 'White' 
    AND ( Action = 'Add' OR Action = 'Transfer Location' )

,而数据库将其解释为

WHERE ( Color = 'White' AND Action = 'Add' )
    OR Action = 'Transfer Location' 

答案 1 :(得分:1)

你可以试试这个

SELECT  COLOR, 
   SUM( CASE WHEN ACTION IN ('Add', 'Transfer Location') THEN XS ELSE -XS END ) AS SUM_XS
FROM BNG
WHERE ACTION IN  ('Add', 'Transfer Location', 'Used/ Damaged')
GROUP BY COLOR

或另一个版本(以避免重复案例......):

SELECT COLOR
, SUM(XS*SIGN) AS SUM_XS
, SUM(SM*SIGN) AS SUM_SM
FROM (
    SELECT COLOR, XS, SM 
           , CASE WHEN ACTION IN ('Add', 'Transfer Location') THEN 1 ELSE -1 END AS SIGN   
    FROM BNG
     WHERE ACTION IN  ('Add', 'Transfer Location', 'Used/ Damaged')
    ) A
GROUP BY COLOR;