Crosstab query with copyright year range as column heading

前提是你 提交于 2020-01-25 00:47:08

问题


I have the following data that I want to create a crosstab query:

 ID   CallNo     CopyrightYear
 1    AH         2000
 2    AB         2000
 3    BC         2000
 4    AH         2002
 5    ZA         2005
 6    BC         2001
 7    AP         2003

This is the crosstab query that I currently have:

 TRANSFORM Count(Table1.[ID]) AS CountOfID
 SELECT Table1.[CallNo], Count(Table1.[ID]) AS [Total Of ID]
 FROM Table1
 GROUP BY Table1.[CallNo]
 PIVOT Table1.[CopyrightYear];

So my question is on how can I group copyright year like from 2000 to 2002 and 2003 to 2005 and so on...

Expected results:

CallNo      2000 to 2002    2003 to 2005
AB              1   
AH              2   
AP                              1
BC              2   
ZA                              1

回答1:


Here is your answer:

TRANSFORM Count(tab1.[ID]) AS CountOfID
SELECT tab1.[CallNo], Count(tab1.[ID]) AS [Total Of ID]
FROM tab1
GROUP BY tab1.[CallNo]
PIVOT CStr(Int(([CopyrightYear]+1)/3)*3-1)+' to '+CStr(Int(([CopyrightYear]+1)/3)*3+1);

In fact, you can just pivot on Int(([CopyrightYear]+1)/3)*3-1. The CStr conversion is mainly done for the cosmetic purposes

For the years 2000 to 2004, 2005 to 2009, etc the expression will be (note that it is value 5 for the 4 year range):

TRANSFORM Count(tab1.[ID]) AS CountOfID
SELECT tab1.[CallNo], Count(tab1.[ID]) AS [Total Of ID]
FROM tab1
GROUP BY tab1.[CallNo]
PIVOT CStr(Int(([CopyrightYear])/5)*5)+' to '+CStr(Int(([CopyrightYear])/5)*5+4)



回答2:


SELECT CallNo,
CASE WHEN COUNT(Copyrightyear =>2000 AND <=2002) AS '2000 to 2002', COUNT(Copyrightyear => 2003 AND <=2005) AS '2003 to 2005'
FROM Table1
GROUP BY CallNo

I'm not sure if this will work.



来源:https://stackoverflow.com/questions/15262565/crosstab-query-with-copyright-year-range-as-column-heading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!