如何根据某些条件获取记录数?

时间:2014-08-06 06:47:10

标签: sql sql-server sql-server-2008

我需要准备一份报告,该报告将显示月份明智的订单数量,其中收货地址=收货地址 和发货地址<>的订单数量收单地址, 例如

年月Same_shipbill Diff_shipbill

2014年1月1768 1233

2014年2月1234 1222

以及当年的等等。

我试过这个查询

SELECT  MAX(DATENAME(YEAR, order_date)) AS [YEAR],
        DATENAME(MONTH, order_date) AS [MONTH],
        COUNT(*) AS SAME_BILL_SHIP
FROM    x_master_order_tb O
         INNER JOIN tbl_Order_Addresses A
           ON A.addressID = O.addressid
WHERE   order_date BETWEEN '2014-01-01 00:00:00:000' AND GETDATE()
         AND wcs_status_id = 1
         AND A.ship_bill = 'Y'
GROUP BY    DATENAME(MONTH, order_date)

此查询仅获取ship = bill地址的计数,不知道如何在此查询中获取“Diff_shipbill”列值? 我只需要翻转条件A.ship_bill ='N'

2 个答案:

答案 0 :(得分:1)

你的意思是你想同时计算ship_bill Y和N这两个吗?

;WITH cte AS
(
 SELECT
   MAX(DATENAME(YEAR, order_date)) AS [YEAR]
  ,DATENAME(MONTH, order_date) AS [MONTH]
  ,MONTH(order_date) AS MONTHNR
  ,CASE WHEN A.ship_bill = 'Y' THEN COUNT(*) END AS SAME_BILL_SHIP
  ,CASE WHEN A.ship_bill = 'N' THEN COUNT(*) END AS DIFF_BILL_SHIP
 FROM x_master_order_tb O
  INNER JOIN tbl_Order_Addresses A
   ON A.addressID = O.addressid
 WHERE order_date BETWEEN '2014-01-01 00:00:00:000' AND GETDATE()
  AND wcs_status_id = 1
 GROUP BY
   DATENAME(MONTH, order_date)
  ,MONTH(order_date)
  ,A.ship_bill
)
SELECT
  YEAR
 ,MONTH
 ,MAX(SAME_BILL_SHIP) AS SAME_BILL_SHIP
 ,MAX(DIFF_BILL_SHIP) AS DIFF_BILL_SHIP
FROM cte
GROUP BY YEAR, MONTH, MONTHNR
ORDER BY MONTHNR

编辑:在A.ship_bill子句中添加了GROUP BY。 编辑:使用CTE可以松开NULL行

答案 1 :(得分:0)

您可以将select子句放在列列表中,这样可以在同一行中为您提供 " same_bill_ship"," diff_bill_ship" 。 看看这是否有帮助。

SELECT  MAX(DATENAME(YEAR, order_date)) AS [YEAR],
    DATENAME(MONTH, order_date) AS [MONTH],
    (SELECT COUNT(*) FROM FROM    x_master_order_tb O1 INNER JOIN tbl_Order_Addresses A1 ON A1.addressID = O1.addressid
        WHERE   order_date BETWEEN '2014-01-01 00:00:00:000' AND GETDATE() AND wcs_status_id = 1 AND A1.ship_bill = 'Y'
        GROUP BY    DATENAME(MONTH, order_date)),
    (SELECT COUNT(*) FROM FROM    x_master_order_tb O2 INNER JOIN tbl_Order_Addresses A2 ON A2.addressID = O2.addressid
        WHERE   order_date BETWEEN '2014-01-01 00:00:00:000' AND GETDATE() AND wcs_status_id = 1 AND A2.ship_bill = 'N'
        GROUP BY    DATENAME(MONTH, order_date))
FROM    x_master_order_tb O
INNER JOIN tbl_Order_Addresses A ON A.addressID = O.addressid
WHERE   order_date BETWEEN '2014-01-01 00:00:00:000' AND GETDATE() AND wcs_status_id = 1
GROUP BY    DATENAME(MONTH, order_date)