sql - 使用联合将不同的查询与不同的组连接起来
问题描述
我有不同的查询(3),它们有不同的条件来获得不同的计数器。
在其中 2 个中,分组是相同的,但在其中一个中没有。
计数线拣选
select
carusrrsppck as 'users',
COUNT(carusrrsppck) AS 'lines picking',
cardepid as 'deposit'
from order_products
where DATEADD(dd, 0, DATEDIFF(dd, 0, carfchcar))
between '20190220' and '20190220'
and cardepid in ('D32', 'DA', 'DA1', 'DB', 'DC', 'DD', 'DE', 'DR')
and carusrrsppck<>''
and ordprdcnt<>0
group by carusrrsppck, cardepid
order by cardepid, COUNT(*) DESC
拒绝计数行
select carusrrsppck as 'users',
COUNT(carusrrsppck) as 'lines denied',
cardepid as 'deposit'
from order_products
where DATEADD(dd, 0, DATEDIFF(dd, 0, carfchcar))
between '20190220' and '20190220'
and ordprdcnt=0
and cardepid in ('D32', 'DA', 'DA1', 'DB', 'DC', 'DD', 'DE', 'DR')
and carusrrsppck<>''
group by carusrrsppck, cardepid
order by cardepid, COUNT(*) DESC
确认计数线
select
carusrcar as 'user',
COUNT(carusrcar) as 'lines confirmed',
cardepid as 'deposit'
from order_products
where DATEADD(dd, 0, DATEDIFF(dd, 0, carfchcar))
between '20190220' and '20190220'
and cardepid in ('D32', 'DA', 'DA1', 'DB', 'DC', 'DD', 'DE', 'DR')
group by carusrcar, cardepid
order by cardepid, COUNT(*) DESC
是否可以加入这 3 个查询,即使它们的分组方式不同,或者我只能加入那些具有相同“分组依据”的查询?
谢谢。
解决方案
Count lines picking
和查询使用相同的Count lines denied
分组列,并且仅在条件上有所不同,因此可以将它们简化为:
SELECT
carusrrsppck as 'users',
SUM(CASE WHEN carusrrsppck <> '' and ordprdcnt <> 0 THEN 1 ELSE 0 END) AS 'lines picking',
SUM(CASE WHEN carusrrsppck <> '' THEN 1 ELSE 0 END) AS 'lines denied',
cardepid AS 'deposit'
FROM order_products
WHERE
DATEADD(dd, 0, DATEDIFF(dd, 0, carfchcar)) BETWEEN '20190220' and '20190220'
AND
cardepid IN ('D32', 'DA', 'DA1', 'DB', 'DC', 'DD', 'DE', 'DR')
GROUP BY carusrrsppck, cardepid
ORDER BY cardepid, COUNT(*) DESC
查询是不同的Count lines confirmed
情况,不能与上述情况相关联。
推荐阅读
- python - 文本文件和换行
- c++ - 用模板函数直接定义非模板函数
- java - 编写程序接收用户输入并检查其拼写
- javascript - 返回字典对象时烧瓶中的响应错误
- c# - 如何将 2 个列表(键列表和值列表)压缩在一起并插入到 mongoDB 集合中?C#
- ios - iOS 13 中 UISplitViewController 的详细信息窗格中的新 UINavigationBar 外观
- inno-setup - 如何在不使用命令行的情况下强制使用 /NORESTART 和其他标志
- c++ - 访问另一个类的数据,其对象在构造函数中作为参数发送
- bootstrap-4 - 在 laravel 中使用模态回复博客评论
- r - 在多面图中更改 geom_line 的颜色