是否可以不使用数据透视功能来透视桌子?

时间:2018-10-23 17:57:55

标签: sql sql-server

我正在尝试编写一个产生两列的查询:月和计数

Month      COUNT
Jan 2018    563
Feb 2018    701
Mar 2018    682
Apr 2018    596
May 2018    395
Jun 2018    538

但是我得到的结果是:

Jan 2018    Feb 2018    Mar 2018    Apr 2018    May 2018    Jun 2018
   563        701         682         596         395          538

很显然,我的查询需要调整。

我尝试使用数据透视功能,但是它太复杂了,所以我想知道是否存在另一种方式编写查询以获取所需格式。

这是我当前的查询:

SELECT

,SUM(CASE WHEN DateRequest BETWEEN '2018-01-01' AND '2018-01-31' THEN 1 ELSE 0 END) as 'Jan 2018'
,SUM(CASE WHEN DateRequest BETWEEN '2018-02-01' AND '2018-02-28' THEN 1 ELSE 0 END) as 'Feb 2018'
,SUM(CASE WHEN DateRequest BETWEEN '2018-03-01' AND '2018-03-31' THEN 1 ELSE 0 END) as 'Mar 2018'
,SUM(CASE WHEN DateRequest BETWEEN '2018-04-01' AND '2018-04-30' THEN 1 ELSE 0 END) as 'Apr 2018'
,SUM(CASE WHEN DateRequest BETWEEN '2018-05-01' AND '2018-05-31' THEN 1 ELSE 0 END) as 'May 2018'
,SUM(CASE WHEN DateRequest BETWEEN '2018-06-01' AND '2018-06-30' THEN 1 ELSE 0 END) as 'Jun 2018'

FROM RequestHeader

感谢您的帮助。谢谢。

2 个答案:

答案 0 :(得分:1)

具有一个派生表,您可以在其中提取年和月部分。 GROUP BY其结果:

select m, y, count(*)
from
(
    select month(DateRequest) as m, year(DateRequest) as y
    from tablename
) dt
group by m, y

如果您的dbms不支持month()year()函数,请尝试使用ANSI SQL的EXTRACT(MONTH FROM DateRequest)EXTRACT(YEAR FROM DateRequest)

答案 1 :(得分:0)

您的代码建议使用SQL Server语法,所以我会尝试:

WITH CTE AS (
     <query>
)
SELECT CC.*
FROM CTE C CROSS APPLY
     ( VALUES ('Jan 2018', [Jan 2018]), 
              ('Feb 2018', [Feb 2018]),
                . . . 
     ) CC(mn, cnt);