您好我需要简化一个选择查询,该查询将产生108个结果的数组。
当前查询如下所示:
SELECT (
SELECT ISNULL(Sum(Dollars), 0)
FROM TableX
WHERE Column3 = 1
AND eventdate BETWEEN @start
AND @end
AND datepart(mm, eventdate) = 1
)
第3列值:1, 4, 3, 14, 17, 10, 9, 13, 6
基本上...... 1-1
,1-2
,1-3
到1-12
然后4-1
,4-2
,4-3
到4-12
等等。
因为我对这些内容不熟悉,我只是复制并粘贴代码并调整了值,但它现在是一个25,000个字符的查询,这太长了。
非常感谢任何有关如何循环这些内容的帮助或指示。
由于
CREATE VIEW TableX (UNIQUEID,FILEKEY,EVENTDATE,GROUP1,GROUP2,GROUP3,PDN,RATE,HOURS,DOLLARS) AS
SELECT 167278 AS UNIQUEID,1 AS FILEKEY,'2014-07-21 00:00:00.000' AS EVENTDATE,1 AS GROUP1,2 AS GROUP2,1 AS GROUP3,14 AS PDN,0 AS RATE,3 AS HOURS,0 AS DOLLARS
UNION ALL
SELECT 167277,1,'2014-07-24 00:00:00.000',1,2,1,1,5,1,5
UNION ALL
SELECT 167276,1,'2014-07-25 00:00:00.000',1,4,1,1,5,1,5
UNION ALL
SELECT 167269,1,'2014-07-07 00:00:00.000',1,2,1,1,5,8,40
UNION ALL
SELECT 167007,1,'2014-07-04 00:00:00.000',1,1,1,4,1,8,8
UNION ALL
SELECT 167006,1,'2014-07-06 00:00:00.000',1,1,1,1,1,1,1
UNION ALL
SELECT 166932,1,'2014-05-26 00:00:00.000',1,1,1,4,1,8,8
UNION ALL
SELECT 166904,1,'2013-12-25 00:00:00.000',1,1,1,4,18.25,8,146
UNION ALL
SELECT 166903,1,'2014-01-01 00:00:00.000',1,1,1,4,18.25,8,146
UNION ALL
SELECT 166902,1,'2013-11-28 00:00:00.000',1,1,1,4,18.25,8,146;
答案 0 :(得分:1)
这可能符合您的需求:
select column3
, datepart(mm, eventdate) monthNum
, isnull(sum(dollars)) dollarSum
from tablex
where eventDate between @start and @end
group by column3,
datepart(mm, eventdate) monthNum
话虽如此,选择月份而不是年份并不是一个好主意。