如何在当前年
中显示所有周(52)我提出了这个问题:
SELECT
COALESCE(IF(DATE_FORMAT(q.date_add, '%Y-%u') IS NULL,
(DATE_FORMAT(q.date_add, '%Y-%u')),
DATE_FORMAT(q.date_add, '%Y WEEK %u'))) AS CurrentDate,
COALESCE(IF(SUM(q.totalExcl) IS NULL,
0,
SUM(q.totalExcl))) AS total
FROM
expoled.ps_oxoquotation_quotationstate_history h
RIGHT JOIN
expoled.ps_oxoquotation_quotation q ON h.idQuotation = q.idQuotation
LEFT JOIN
expoled.ps_employee e ON h.idEmployee = e.id_employee
INNER JOIN
expoled.ps_sv_employee_meta m ON h.idEmployee = m.id_employee
WHERE
h.idEmployee = 39
AND YEAR(q.date_add) = YEAR(UTC_TIMESTAMP())
AND h.idQuotationState = 3
GROUP BY IFNULL(CurrentDate, '')
我想我需要在这里做点什么:
SELECT
IFNULL(DATE_FORMAT(q.date_add, '%Y WEEK %u'), 0) AS CurrentDate,
IFNULL(SUM(q.totalExcl),0) AS total
FROM
我已经尝试过放置IFNULL,但这给了我相同的结果
这就是我现在所得到的:
显示当前几周从5周到16周。 第1周到第4周也没有任何内容,因为没有数据。而且它只需显示一个简单的零(0)
所以我想要的是它需要从第1周到第52周显示标准,如果没有数据只是0
该查询现在正常运行,没有任何错误。
答案 0 :(得分:1)
为了获得固定的周数,没有特定的表,我尝试了这个。 表XX1只是为了进行测试,可以用你的一个表替换。如果它有多个记录> = 366,你可以消除CROSS JOIN。
CREATE TABLE XX1 (id INT);
INSERT INTO XX1 VALUES (1);
INSERT INTO XX1 VALUES (2);
INSERT INTO XX1 VALUES (3);
INSERT INTO XX1 VALUES (4);
INSERT INTO XX1 VALUES (5);
SELECT DISTINCT DATE_FORMAT(RN, '%Y w%u') AS CURR_WEEK
FROM
(SELECT @RN:=DATE_ADD(str_to_date( CONCAT(YEAR(UTC_TIMESTAMP()) ,'0101'), '%Y%m%d'), INTERVAL -1 DAY) AS RN
UNION ALL
SELECT @RN:=DATE_ADD(@RN, INTERVAL 1 DAY) AS RN
FROM (SELECT 1 AS DUM FROM XX1
CROSS JOIN XX1 X2
CROSS JOIN XX1 X3
CROSS JOIN XX1 X4
) Y LIMIT 366
) X
WHERE YEAR(RN)=YEAR(UTC_TIMESTAMP())
ORDER BY 1;
DROP TABLE XX1 ;
输出:
CURR_WEEK
1 2017 w00
2 2017 w01
3 2017 w02
4 2017 w03
5 2017 w04
...
51 2017 w50
52 2017 w51
53 2017 w52
我认为您可以使用它来代替您的查询(我当然无法对您的查询进行任何测试)
其他(希望最后)版本:
SELECT Y.CURR_WEEK,
COALESCE(SUM(qh.totalExcl), 0) AS total
FROM
(SELECT DISTINCT DATE_FORMAT(RN, '%Y-%u') AS CURR_WEEK
FROM
(SELECT @RN:=DATE_ADD(str_to_date( CONCAT(YEAR(UTC_TIMESTAMP()) ,'0101'), '%Y%m%d'), INTERVAL -1 DAY) AS RN
UNION ALL
SELECT @RN:=DATE_ADD(@RN, INTERVAL 1 DAY) AS RN
FROM XX1
CROSS JOIN XX1 X2
CROSS JOIN XX1 X3
CROSS JOIN XX1 X4
) X
WHERE YEAR(RN)=YEAR(UTC_TIMESTAMP())
) Y
LEFT JOIN (SELECT q.date_add, q.totalExcl, h.idEmployee
FROM expoled.ps_oxoquotation_quotation q
INNER JOIN expoled.ps_oxoquotation_quotationstate_history h ON h.idQuotation = q.idQuotation
WHERE h.idEmployee = 39 AND h.idQuotationState = 3) qh ON DATE_FORMAT(qh.date_add, '%Y-%u')=Y.CURR_WEEK
/* are these useless? */
LEFT JOIN expoled.ps_employee e ON qh.idEmployee = e.id_employee
LEFT JOIN expoled.ps_sv_employee_meta m ON qh.idEmployee = m.id_employee
GROUP BY Y.CURR_WEEK
答案 1 :(得分:1)
在MariaDB中,建立一个几周的表格非常容易:
mysql> SELECT ('2017-01-02' + INTERVAL seq WEEK) AS wk FROM seq_0_to_53;
+------------+
| wk |
+------------+
| 2017-01-02 |
| 2017-01-09 |
| 2017-01-16 |
| 2017-01-23 |
| 2017-01-30 |
| 2017-02-06 |
| 2017-02-13 |
| 2017-02-20 |
...
基于此,你可以:
JOIN
到您的桌子并根据需要使用wk
。WHERE wk BETWEEN ...
CONCAT('2017 WEEK ', seq) AS iso
之类的内容,您可以获得所请求的语法。