使用具有不同条件的多个SQL select语句

时间:2017-06-30 20:41:06

标签: sql

我正在制作一份报告,为每位员工输出不同的统计数据。我的老板想看看发货订单需要多长时间。我们是一家在线零售商,负责处理从单个项目到数百或数千个订单的订单。超过12件商品的订单被视为"批量"订单,其他任何东西都被视为"小"订购。用于计算的所有数据都来自同一个表,但是要提取的数据的限制是不同的。

这些是他想要收集的每个数据的要求。

SELECT AVG(bulkFTS) as bulkMODFTS
FROM cartHead
WHERE  rateFactor <> -1 AND rateFactor <> 0 AND bulkStartDate <> NULL
SELECT count(idOrder) as totalOrders
FROM cartHead
WHERE rateFactor <> -1 
SELECT count(idOrder) as overFTS
FROM cartHead
WHERE smallFTS > 27 AND rateFactor <> -1 AND rateFactor <> 0 AND bulkGlassCount = '' 
SELECT round(sum(rateFactor),1) as totalFactors
FROM cartHead
WHERE rateFactor <> -1 AND rateFactor <> 0 
SELECT ROUND(AVG(FTStime),2) as avgFTS
FROM cartHead
WHERE rateFactor <> -1 AND rateFactor <> 0 AND bulkGlassCount = ''

他们所有人也必须限于&#34; WHERE graphicsTeam = x AND ordercompletedate BETWEEN date1 AND date2&#34;

有一种简单的方法吗?我尝试将每一个设置为自己的功能,但它不仅需要非常长的时间来加载,它也不能始终如一地工作。许多限制是交叉的,但每一个都需要不同的数字条件才能准确。

1 个答案:

答案 0 :(得分:0)

在一个查询中执行此操作。像这样:

SELECT AVG(CASE WHEN bulkStartDate <> NULL THEN bulkFTS END) as bulkMODFTS,
       count(idOrder) as totalOrders
       count(case when rateFactor <> 0 AND smallFTS > 27 and bulkGlassCount = '' then idOrder end) as overFTS
      round(SUM(CASE WHEN rateFactor <> 0 AND THEN rateFactor END), 1) as totalFactors,
       ROUND(AVG(CASE WHEN rateFactor <> 0 AND bulkGlassCount = '' THEN FTStime END), 2) as avgFTS
FROM cartHead
WHERE rateFactor <> -1 AND 
      graphicsTeam = x AND ordercompletedate BETWEEN date1 AND date2"