0

目前,我将数据分解为月份间隔。这就是我希望它显示的方式,但我试图只显示整个表格中ordered_by总数为 300 或更多的那些。LoadCount所以基本上,我想扔掉任何ordered_by没有至少 300

SELECT YEAR(stop.actual_arrival) AS Year, MONTH(stop.actual_arrival) AS Month, COUNT(stop.id) AS DeliveryCount, orders.ordered_by, COUNT(DISTINCT orders.id) 
              AS LoadCount
FROM     stop INNER JOIN
                  (SELECT company_id, order_id, tractor_id
                   FROM      billing_history
                   GROUP BY order_id, tractor_id, company_id) AS derivedtbl_1 ON stop.company_id = derivedtbl_1.company_id AND stop.order_id = derivedtbl_1.order_id INNER JOIN
              tractor ON derivedtbl_1.company_id = tractor.company_id AND derivedtbl_1.tractor_id = tractor.id INNER JOIN
              orders ON derivedtbl_1.company_id = orders.company_id AND derivedtbl_1.order_id = orders.id
WHERE  (orders.order_type_id IN ('12', '13')) AND (stop.stop_type = 'SO') AND (stop.actual_arrival >= DATEADD(month, - 18, GETDATE())) AND (orders.customer_id = 945000) AND 
              (orders.ordered_by IS NOT NULL)
GROUP BY YEAR(stop.actual_arrival), MONTH(stop.actual_arrival), orders.ordered_by
ORDER BY Year, Month, orders.ordered_by

我一直在来回考虑是否需要派生表或什么......任何帮助将不胜感激。多谢你们。

我试图扔掉ordered_by总和不超过 300 的任何一个。如果它们在整个板上加起来达到 300,我希望它们被显示,即使它们在那条线上是 5。

4

2 回答 2

0

如果我正确理解您的问题,您可以使用 select 子句中的 CASE 语句来显示 NULL 或 orders.ordered_by,具体取决于 LoadCount 的值。这是一个包含一些示例的页面:http: //msdn.microsoft.com/en-us/library/ms181765 (v=sql.110).aspx

于 2013-05-31T18:23:20.297 回答
0

如果您要做的只是丢弃任何不ordered_by小于 300 的结果,则可以使用HAVING带有GROUP BY

<snip...>
GROUP BY YEAR(stop.actual_arrival), MONTH(stop.actual_arrival), orders.ordered_by
HAVING orders.ordered_by >= 300
ORDER BY Year, Month, orders.ordered_by
于 2013-05-31T18:35:15.713 回答