我有2个表ticket
和article
,我有这个查询:
SELECT hour(ticket.stats_iso) hour_num,
IF(MINUTE(ticket.stats_iso) < 30, 0, 1) interval_num,
min(ticket.stats_iso) interval_begin,
max(ticket.stats_iso) interval_end,
count(ticket.id) countid,
sum(ticket.montantTTC) sum_subtotal,
(sum(ticket.montantTTC)/count(ticket.id)) as moy
FROM ticket
WHERE ticket.annule = 0
AND ticket.stats_iso
BETWEEN '2012-01-01 00:00:00' AND '2012-01-01 23:59:59'
GROUP BY hour_num, interval_num
ORDER BY hour_num, interval_num
我有关于ticket
的数量和montantTTC
的总和的统计信息。
我希望有article
s的数量,然后我加入了:
SELECT hour(ticket.stats_iso) hour_num,
IF(MINUTE(ticket.stats_iso) < 30, 0, 1) interval_num,
min(ticket.stats_iso) interval_begin,
max(ticket.stats_iso) interval_end,
count(DISTINCT ticket.id) countid,
sum(ticket.montantTTC) sum_subtotal,
(sum(ticket.montantTTC)/count(ticket.id)) as moy, count(article.id)
FROM ticket, article
WHERE ticket.annule = 0
AND ticket.stats_iso
BETWEEN '2012-01-01 00:00:00' AND '2012-01-01 23:59:59'
AND ticket.uid = article.uid_ticket
GROUP BY hour_num, interval_num
ORDER BY hour_num, interval_num
它的工作原理但是sum(ticket.montantTTC) sum_subtotal
变为假...(实际上,加入它会导致许多重复ticket
因为1 ticket
有很多article
s
count(ticket.id) countid
也有问题,但我可以写count(DISTINCT ticket.id) countid
。
是否存在一种在sum(ticket.montantTTC) sum_subtotal
上制作条件的方式?
示例(当然,不起作用):sum(if ticket.id IS DISTINCT then ticket.montantTTC) sum_subtotal
非常感谢。
答案 0 :(得分:1)
SELECT HOUR(t.stats_iso) hour_num,
ROUND(MINUTE(t.stats_iso)/60) interval_num,
MIN(t.stats_iso) interval_begin,
MAX(t.stats_iso) interval_end,
COUNT(t.id) countid,
SUM(t.montantTTC) sum_subtotal,
SUM(t.montantTTC)/count(t.id) moy,
SUM(COALESCE(a.article_count,0)) article_count
FROM ticket t
LEFT JOIN (
SELECT uid_ticket, COUNT(*) article_count
FROM article
GROUP BY uid_ticket
) a
ON t.uid = a.uid_ticket
WHERE t.annule = 0
AND t.stats_iso BETWEEN '2012-01-01' AND '2012-01-02'
GROUP BY hour_num, interval_num
ORDER BY hour_num, interval_num