我一直在使用COUNT(value) OVER (PARTITION BY anothervalue)
,我喜欢它从我的数据库中提取结果的速度有多快。我现在试图解决这个问题,这样我就可以创建一个表格,向我显示多个计数 - 每个月一个,并排。我不确定是否有可能,但想在这里查看。我在网上浏览了一下,但之前没有找到任何问题的例子,所以没有线索。
以下是我目前的情况:
SELECT DISTINCT
TBL.CATEGORY as 'Category Name',
COUNT(TBL.ROW_ID) OVER (PARTITION BY TBL.CATEGORY) as 'Rows in Category'
FROM
MYDB.TBL
WHERE
TBL.FIELD1 = 'something'
AND TBL.FIELD2 = 'somethingelse'
AND TBL.CREATED >= '2014-01-01'
ORDER BY [Rows in Category] desc
给了我一张可爱的桌子:
Category Name |Rows in Category
ABC | 166
CBA | 137
CCC | 112
我现在试图获得的是按月细分所以我的输出结果看起来像这样(不一定是精确的,标题可以随机播放):
JANUARY |FEBRUARY
Category Name |Rows in Category | Category Name |Rows in Category
ABC | 162 | CBA | 51
CBA | 86 | CCC | 32
CCC | 70 | ABC | 4
当我尝试添加GROUP BY
时,它会抛出关于聚合函数中未包含的内容的错误。
如果必须的话,我可以将查询叠加在一起,并将每个查询限制为只显示一个月,但这似乎是很多重复的代码,如果它,我更喜欢并排查看可以做到。
有什么想法吗?
答案 0 :(得分:2)
格式与您描述的不完全相同。但这是显示结果的正常方式,所有信息都已包含在内,请确保一次显示的时间不超过1年。
试试这个:
;WITH x AS
(
SELECT TBL.CATEGORY, TBL.ROW_ID, datename(month, TBL.CREATED) month
FROM
MYDB.TBL
WHERE
TBL.FIELD1 = 'something'
AND TBL.FIELD2 = 'somethingelse'
AND TBL.CREATED >= '2014-01-01'
AND TBL.CREATED < '2015-01-01'
)
SELECT CATEGORY as 'Category Name', [January],[February]
FROM x
PIVOT(
count([ROW_ID])
FOR month
in([January],[February])
)AS p
答案 1 :(得分:0)
@ t-clausen.dk感谢您的帮助。我以前没有使用过coalesce,所以我今天学到了一些有用的东西。最后,因为我发现我需要一个完整的列,我添加了一个YTD列,并且能够按此顺序。
想要发布最终结果以防其他人使用:
WITH X AS
(
SELECT
tbl.category,
tbl.row_id,
DATENAME(MONTH, tbl.created) MONTH,
COUNT(tbl.row_id) OVER (PARTITION BY tbl.category) AS 'YTD'
FROM
db.tbl
WHERE
tbl.randomcolumn = 'something specific'
AND tbl.anothercolumn = 'something else specific'
AND created >= '2014-01-01'
AND created < '2015-01-01'
)
SELECT
category AS 'Category Name',
[January], [February], [March], [April], [May], [June], [July], [August], [September], [October], [November], [December],
[YTD]
FROM X
PIVOT
(COUNT([row_id])
FOR MONTH
in([January], [February], [March], [April], [May], [June], [July], [August], [September], [October], [November], [December])
)AS P
ORDER BY [YTD] DESC
如果要重新调整此查询的用途,请为您自己的db / table中的等效项切换小写部分。