作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有两个 MYSQL 查询,我正在尝试将其合并为一个,这是第一个 -
SELECT
`Your_Name` as agentname,
sum(`Sale_Amount`) as todaysales,
COUNT(*) as NoSales
FROM mp_wp_sales_tracking
WHERE `created` BETWEEN CURDATE() AND NOW()
GROUP BY agentname
第二个是相同的查询,只是针对前一天
SELECT
`Your_Name` as agentname,
sum(`Sale_Amount`) as yesterdaysales,
COUNT(*) as YesterdayNoSales
FROM mp_wp_sales_tracking
WHERE `created` BETWEEN DATE_SUB(CURDATE(),INTERVAL 1 DAY)
AND ADDTIME(DATE_SUB(CURDATE(),INTERVAL 1 DAY),'23:59:59.50')
GROUP BY agentname
现在我想做的是实现如下所示的内容(根据 MYSQL 中的别名的 header )
| agentname | todaysales | nosales | yesterdaysales | yesterdaynosales |
我已经尝试过使用 Inner Join,但不断收到 SQL 错误,我不知道在哪里打开它,因为对复杂的 MYSQL 查询相当陌生。
最佳答案
我可以想到一种方法来合并这两个查询并对结果使用条件聚合
SELECT `Your_Name` as agentname,
SUM( CASE WHEN
`created` BETWEEN DATE_SUB(CURDATE(),INTERVAL 1 DAY) AND ADDTIME(DATE_SUB(CURDATE(),INTERVAL 1 DAY),'23:59:59.50')
THEN `Sale_Amount`
ELSE 0 END
) as yesterdaysales,
SUM(`created` BETWEEN DATE_SUB(CURDATE(),INTERVAL 1 DAY) AND ADDTIME(DATE_SUB(CURDATE(),INTERVAL 1 DAY),'23:59:59.50') ) as YesterdayNoSales ,
SUM(CASE WHEN
`created` BETWEEN CURDATE() AND NOW()
THEN `Sale_Amount`
ELSE 0 END
) as todaysales,
SUM(`created` BETWEEN CURDATE() AND NOW() ) as NoSales
FROM mp_wp_sales_tracking
WHERE `created` BETWEEN DATE_SUB(CURDATE(),INTERVAL 1 DAY) AND ADDTIME(DATE_SUB(CURDATE(),INTERVAL 1 DAY),'23:59:59.50')
OR `created` BETWEEN CURDATE() AND NOW()
GROUP BY agentname
关于MYSQL 多选、Where 和 Group By 对同一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46465244/
我是一名优秀的程序员,十分优秀!