左加入不符合条件

时间:2016-01-26 07:24:18

标签: mysql

我有两个柜台,一个是单位,一个是废物。  我需要提取计时器的总和并按年份分开  Left Join有点起作用,但是只要我把一个where条件分开定时器,那么思想就会崩溃。
 有人可以查看一下,并指出我正确的方向吗?
 谢谢。  杰米。

 SELECT year(counts.ts) as SalesYear, Q1.Res1 AS units, Q2.Res2 as rate
 FROM 
 (counts
 LEFT JOIN (SELECT (counts.ts), SUM(counts.count) AS Res1 
 FROM counts where counts.`name` = 104 and counts.count > 0 ) AS Q1 ON (counts.ts) = Q1.ts) 

 LEFT JOIN (SELECT (counts.ts), Sum(counts.count) AS Res2
 FROM counts where counts.`name` = 107 and counts.count > 0) AS Q2 ON (counts.ts) = Q2.ts

 GROUP BY year(counts.ts)
 order by year(counts.ts) 

1 个答案:

答案 0 :(得分:1)

我相信你可以像这样使用“条件聚合”:

SELECT
      YEAR(counts.ts) as SalesYear
    , SUM(case when counts.count = 104 then counts.count else 0 end) AS Res1 
    , SUM(case when counts.count = 107 then counts.count else 0 end) AS Res2
FROM counts 
WHERE counts.name IN (104,107)
      AND counts.count > 0 
GROUP BY YEAR(counts.ts) 
ORDER BY YEAR(counts.ts)
;

由于样本数据现已通过sqlfiddle实例提供,因此以下内容现已相关。请注意,上面的查询与问题一样,问题是条件错误地基于列counts.count而不是counts.name。一旦纠正,完全相同的查询结构就会提供结果。 (请注意,如果没有看到数据,我就无法知道这一点。)

SQL Fiddle

MySQL 5.6架构设置

DROP TABLE IF EXISTS `counts`;
CREATE TABLE `counts` (
  `id` int(15) NOT NULL AUTO_INCREMENT,
  `name` varchar(16) DEFAULT NULL,
  `ts` datetime DEFAULT NULL,
  `count` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `UniqueDataIndex` (`name`,`ts`,`count`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=475152 DEFAULT CHARSET=utf8;

INSERT INTO `counts` VALUES ('475026', '107             ', '2015-01-27 10:18:00', '40');
INSERT INTO `counts` VALUES ('475032', '104             ', '2015-01-27 10:20:00', '11');
INSERT INTO `counts` VALUES ('475039', '107             ', '2015-01-27 10:22:00', '109');
INSERT INTO `counts` VALUES ('475046', '104             ', '2015-01-27 10:24:00', '92');
INSERT INTO `counts` VALUES ('475052', '107             ', '2015-01-27 10:26:00', '124');
INSERT INTO `counts` VALUES ('475058', '104             ', '2016-01-27 10:28:00', '98');
INSERT INTO `counts` VALUES ('475069', '107             ', '2016-01-27 10:32:00', '77');
INSERT INTO `counts` VALUES ('475075', '104             ', '2016-01-27 10:34:00', '44');
INSERT INTO `counts` VALUES ('475081', '107             ', '2016-01-27 10:36:00', '43');
INSERT INTO `counts` VALUES ('475087', '104             ', '2016-01-27 10:38:00', '89');
INSERT INTO `counts` VALUES ('475093', '107             ', '2016-01-27 10:40:00', '89');

查询1

SELECT
      YEAR(counts.ts) as SalesYear
    , SUM(case when counts.name = '104' then counts.count else 0 end) AS Res1 
    , SUM(case when counts.name = '107' then counts.count else 0 end) AS Res2
FROM counts 
WHERE counts.name IN ('104','107')
      AND counts.count > 0 
GROUP BY YEAR(counts.ts) 
ORDER BY YEAR(counts.ts)

<强> Results

| SalesYear | Res1 | Res2 |
|-----------|------|------|
|      2015 |  103 |  273 |
|      2016 |  231 |  209 |