2

我必须以以下格式显示数据:

在此处输入图像描述

假设我选择 08-2013 日期来显示数据。实际上这是一个消费者数据。因此,本月列应计算 2013 年 8 月的数据(即 Count OR SUM),而从 April列应计算2013 年 4月至 2013 年 8 月的数据(即 Count OR SUM) 。

所以现在我的问题是我如何编写 T-SQL 来获得这个结果集。我可以分别计算本月数据和四月数据,但如何将这两个结果合并为单个结果集。

我是否必须创建一个表才能获得此结果集。

附言

好的,所以我以第一行为例1) 示例文本 1仅代表本月四月起的单独计算

DECLARE @BILL_DATE DATETIME
SET @BILL_DATE= '2013-08-15'
--Seprate result set for THIS MONTH and ROW For Sample text 1
SELECT 
ISNULL(COUNT(CASE WHEN CAT_CODE='1' THEN C.CONSUMER_NO END),0) AS CAT_1_THIS_MONTH,
ISNULL(COUNT(CASE WHEN CAT_CODE='2' THEN C.CONSUMER_NO END),0) AS CAT_2_THIS_MONTH,
ISNULL(COUNT(CASE WHEN CAT_CODE='3' THEN C.CONSUMER_NO END),0) AS CAT_3_THIS_MONTH
FROM CONSUMER C
INNER JOIN BILLING B ON C.CONSUMER_NO = B.CONSUMER_NO
WHERE B.BILL_DATE = @BILL_DATE AND (more condition will be as per For Sample text 1)
--Seprate result set for FROM APRIL and ROW For Sample text 1
SELECT 
ISNULL(SUM(CASE WHEN CAT_CODE='1' THEN C.UNIT END),0) AS CAT_1_FROM_APRIL,
ISNULL(SUM(CASE WHEN CAT_CODE='2' THEN C.UNIT END),0) AS CAT_2_FROM_APRIL,
ISNULL(SUM(CASE WHEN CAT_CODE='3' THEN C.UNIT END),0) AS CAT_3_FROM_APRIL
FROM CONSUMER C
INNER JOIN BILLING B ON C.CONSUMER_NO = B.CONSUMER_NO
WHERE B.BILL_DATE BETWEEN '2013-04-01' AND @BILL_DATE  AND (more condition will be as per For Sample text 1)

现在我的目标是在两列中的一行中显示这两个单独的结果(即本月和四月起)

4

1 回答 1

1

您需要在 WHERE 子句中包含整个期间的条件因此,您可以使用嵌套的 case 表达式来检查月份 August

DECLARE @BILL_DATE datetime,
        @sDate datetime, 
        @eDate datetime
SET @BILL_DATE = '20130815'        
SET @sDate = DATEADD(MONTH, DATEDIFF(MONTH, 0, @BILL_DATE), 0)
SET @eDate = DATEADD(MONTH, 1, @sDate)

SELECT COUNT(CASE WHEN B.BILL_DATE >= @sDate AND B.BILL_DATE < @eDate 
                  THEN CASE WHEN CAT_CODE='1' 
                            THEN C.CONSUMER_NO END END) AS CAT_1_THIS_MONTH,       
       SUM(CASE WHEN CAT_CODE='1' THEN C.UNIT END) AS CAT_1_FROM_APRIL,
       COUNT(CASE WHEN B.BILL_DATE >= @sDate AND B.BILL_DATE < @eDate 
                  THEN CASE WHEN CAT_CODE='2' 
                            THEN C.CONSUMER_NO END END) AS CAT_2_THIS_MONTH,
       SUM(CASE WHEN CAT_CODE='2' THEN C.UNIT END) AS CAT_2_FROM_APRIL,
       COUNT(CASE WHEN B.BILL_DATE >= @sDate AND B.BILL_DATE < @eDate 
                  THEN CASE WHEN CAT_CODE='3' 
                            THEN C.CONSUMER_NO END END) AS CAT_3_THIS_MONTH,              
       SUM(CASE WHEN CAT_CODE='3' THEN C.UNIT END) AS CAT_3_FROM_APRIL
FROM CONSUMER C INNER JOIN BILLING B ON C.CONSUMER_NO = B.CONSUMER_NO
WHERE B.BILL_DATE >= '20130401 00:00:00' AND B.BILL_DATE < @eDate
  AND (more condition will be as per For Sample text 1)
于 2013-09-05T07:20:03.270 回答