简单的SQL JOIN基于其他字段获取一个字段的值> 0

时间:2015-03-23 15:49:38

标签: sql

有一个表有字段Country,Dc13,Jn14 .... Dc14。 Dc13和Dc14上的值是0或> 0。

要使用值获取相同的国家/地区,请使用可正常运行的查询:

SELECT Tb1.Country FROM Tb1 WHERE (((Tb1.Dc13)>0) AND ((Tb1.Dc14)>0))
GROUP BY Tb1.Country

我试图比较并获得在Dc14中有价值但在Dc13中为0的国家/地区。以下我无法配置的东西:

SELECT Tb1.Country
FROM Tb1
JOIN Tb1.Dc14 ON Tb1.Dc13 = Tb1.Dc14
WHERE (((Tb1.Dc13)>0) AND ((Tb1.Dc14)>0))
GROUP BY Tb1.Country

4 个答案:

答案 0 :(得分:0)

我想你想要:

SELECT Tb1.Country 
FROM Tb1 WHERE (((Tb1.Dc13)=0) AND ((Tb1.Dc14)>0))
GROUP BY Tb1.Country

答案 1 :(得分:0)

据我所知,你在一张桌子上进行查询?

我认为你可以做到这一点

SELECT Country
FROM Tb1
WHERE Dc13 = 0 AND Dc14 > 0
GROUP BY Country

答案 2 :(得分:0)

我发现环顾四周的唯一方法是创建2个表:

SELECT Tb1.Country INTO Tb12  
FROM Tb1   
WHERE (((Tb1.Dc14)>0))
GROUP BY Tb1.Country;

并且正在运行:

SELECT 
  Tb11.Country,
"Country in Dc 13, but not Dc14" as Result
  FROM
 Tb11 
 LEFT JOIN Tb12 ON
   Tb11.Country = Tb12.Country
  WHERE Tb12.Country IS NULL
 UNION
 SELECT
 Tb12.Country,
      "Country in Dc14, but not Dc13"
  FROM
  Tb12
  LEFT JOIN Tb11 ON
   Tb12.Country = Tb11.Country
  WHERE Tb11.country IS NULL
 UNION
 SELECT
 Tb12.Country,
  "Country is in both Periods"
  FROM
 Tb12
 INNER JOIN Tb11 ON
          Tb12.Country = Tb11.Country

答案 3 :(得分:0)

SELECT "Dc13 Only" AS Status, Country
 FROM Tb1 AS T1
 WHERE Dc13 IS NOT NULL
 AND NOT EXISTS
 (SELECT *
    FROM Tb1 As T2
    WHERE T2.Country = T1.Country
    AND Dc14 IS NOT NULL)
 UNION
SELECT "Dc14 Only", Country
FROM Tb1 AS T1
WHERE Dc14 IS NOT NULL
AND NOT EXISTS
     (SELECT *
     FROM Tb1 As T2
     WHERE T2.Country = T1.Country
     AND Dc13 IS NOT NULL)
 UNION
 SELECT "DC13 & Dc14", Country
 FROM Tb1
 WHERE Dc13 IS NOT NULL
 AND Dc14 IS NOT NULL
 UNION
 SELECT "Neither", Country
 FROM Tb1 AS T1
 WHERE NOT EXISTS
 (SELECT *
  FROM Tb1 As T2
  WHERE T2.Country = T1.Country
  AND (Dc13 IS NOT NULL
  OR Dc14 IS NOT NULL))
  ORDER BY Status, Country;