问题
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