我必须以下列格式显示数据:
假设我选择08 - 2013日期显示数据。实际上这是消费者数据。所以本月列应该计算2013年8月的数据(即计数OR SUM),从4月列应该计算数据(即计数或SUM) )从 2013年4月至2013年8月。
所以现在我的问题是如何编写T-SQL来获取此结果集。 我可以单独计算本月数据和 4月数据,但如何将这两个数据合并为单个结果集。
我是否必须创建一个表来获取此结果集。
PS
好的,所以我举了第一行的示例 1)示例文本1 只是为了表示本月和从4月 <的个别计算/ p>
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月)
答案 0 :(得分:1)
您需要一个包含WHERE子句中整个句点的条件 因此,您可以使用嵌套的case表达式来检查8月份
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)