我想知道是否有办法在SQL中获取最后两周及其金额,我解释一下:
以下查询以这种方式告诉我过去两周的产品数量:
SELECT pr_products.product,
WEEKOFYEAR(pf_harvest.date) AS week,
SUM(pf_harvest.quantity) AS quantity
FROM pf_harvest
INNER JOIN pr_products ON pr_products.id = pf_harvest.id_product
WHERE pf_harvest.date BETWEEN '2016-08-15' AND '2016-08-28'
AND pf_harvest.id_tenant = 1
AND pf_harvest.id_product = 1
GROUP BY product, WEEKOFYEAR(pf_harvest.date);
我得到的结果如下:
-------------------------------------
product | week | quantity |
-------------------------------------
ROSA PINK | 33 | 1076000 |
-------------------------------------
ROSA PINK | 34 | 1094025 |
-------------------------------------
没关系,问题是我希望查询结果给我留下这样的东西:
-------------------------------------
product | week1 | week2 |
-------------------------------------
ROSA PINK | 1076000 | 1094025 |
-------------------------------------
这是为了获得在第33周和第34周分组的单个产品的数量,我不知道是否可以这样做,谢谢!
答案 0 :(得分:1)
你应该使用条件aggergation。每列仅聚合其周。因此,一次通过一个查询将获得两个聚合。
describe('myDirective', function () {
'use strict';
var element,
dirCtrlScp,
$compile,
$rootScope,
$scope;
beforeEach(module('myApp'));
beforeEach(inject(function (_$compile_, _$rootScope_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
element = compileElement();
}));
function compileElement() {
var element = angular.element('<my-directive></my-directive>');
var compiledElement = $compile(element)($scope);
dirCtrlScp = element.controller;
$scope.$digest();
return compiledElement;
}
it('should execute f', function () {
dirCtrlScp.f();
expect(dirCtrlScp.value).toBe(true); // there we can access to isolate scope from directive;
});
});
答案 1 :(得分:1)
实现类似Union Select的使用
SELECT pr_products.product,
SUM(pf_harvest.quantity) AS week1
FROM pf_harvest
INNER JOIN pr_products ON pr_products.id = pf_harvest.id_product
WHERE pf_harvest.date BETWEEN '2016-08-15' AND '2016-08-21'
AND pf_harvest.id_tenant = 1
AND pf_harvest.id_product = 1
GROUP BY product, WEEKOFYEAR(pf_harvest.date);
UNION
SELECT
SUM(pf_harvest.quantity) AS week2
FROM pf_harvest
INNER JOIN pr_products ON pr_products.id = pf_harvest.id_product
WHERE pf_harvest.date BETWEEN '2016-08-21' AND '2016-08-28'
AND pf_harvest.id_tenant = 1
AND pf_harvest.id_product = 1
GROUP BY product, WEEKOFYEAR(pf_harvest.date);
第一个选择获取第1周的数据,第二个获取第2周的数据。
有关联盟的更多信息,请参阅mysql
答案 2 :(得分:0)
我确信这不是最好的方法,但你可以使用偏移合并来引入它。如果内存服务,这应该将字段标记为product | week | week(1)| week(2)| .. ..
答案 3 :(得分:0)
你有没有尝试过这样的事情:
SELECT pr_products.product,
SUM(h1.quantity) AS Week1,
SUM(h2.quantity) AS Week2
FROM pr_product
LEFT JOIN pf_harvest h1 ON pr_products.id = h1.id_product ,
LEFT JOIN pf_harvest h2 ON pr_products.id = h2.id_product
WHERE
( h1.date BETWEEN '2016-08-15' AND '2016-08-21'
AND h1.id_tenant = 1
AND h1.id_product = 1 )
OR
( h2.date BETWEEN '2016-08-22' AND '2016-08-28'
AND h2.id_tenant = 1
AND h2.id_product = 1 )
GROUP BY product ;