没有聚合函数的透视

时间:2016-04-08 12:42:12

标签: sql sql-server pivot aggregate-functions

是否可以从Pivot查询中删除Aggregate函数。

我对此查询有疑问,因为如果我的员工生日相同,则只会出现第一个。

SELECT * 
FROM ( SELECT lastname +' '+ firstname as name, Birthdate, 
        CASE
        WHEN DATEPART(yyyy,Birthdate) BETWEEN 1930 AND 1939 THEN 1930
        WHEN DATEPART(yyyy,Birthdate) BETWEEN 1940 AND 1949 THEN 1940
        WHEN DATEPART(yyyy,Birthdate) BETWEEN 1950 AND 1959 THEN 1950
        WHEN DATEPART(yyyy,Birthdate) BETWEEN 1960 AND 1969 THEN 1960
        WHEN DATEPART(yyyy,Birthdate) BETWEEN 1970 AND 1979 THEN 1970
        WHEN DATEPART(yyyy,Birthdate) BETWEEN 1980 AND 1989 THEN 1980
        WHEN DATEPART(yyyy,Birthdate) BETWEEN 1990 AND 1999 THEN 1990
        WHEN DATEPART(yyyy,Birthdate) BETWEEN 2000 AND 2009 THEN 2000
        ELSE DATEPART(yyyy,Birthdate) END as [BDate] FROM ADR_Address 

) as s
PIVOT
(
    MAX(name)
    FOR [BDate] IN ([1930],[1940],[1950],[1960],[1970],[1980],[1990],[2000])
)AS pvt
WHERE Birthdate IS NOT NULL ORDER BY Birthdate

2 个答案:

答案 0 :(得分:0)

如果我理解您的代码是正确的,您可以为透视行添加另一个分隔符,例如行号。因此,与生日相比,您将在旋转的行上拥有生日+原始行号。

通过这种方式,您可以在技术上显示所有名称,但这种枢轴仍然很奇怪:

SELECT * 
FROM ( SELECT lastname +' '+ firstname as name, Birthdate, 
    CASE
    WHEN DATEPART(yyyy,Birthdate) BETWEEN 1930 AND 1939 THEN 1930
    WHEN DATEPART(yyyy,Birthdate) BETWEEN 1940 AND 1949 THEN 1940
    WHEN DATEPART(yyyy,Birthdate) BETWEEN 1950 AND 1959 THEN 1950
    WHEN DATEPART(yyyy,Birthdate) BETWEEN 1960 AND 1969 THEN 1960
    WHEN DATEPART(yyyy,Birthdate) BETWEEN 1970 AND 1979 THEN 1970
    WHEN DATEPART(yyyy,Birthdate) BETWEEN 1980 AND 1989 THEN 1980
    WHEN DATEPART(yyyy,Birthdate) BETWEEN 1990 AND 1999 THEN 1990
    WHEN DATEPART(yyyy,Birthdate) BETWEEN 2000 AND 2009 THEN 2000
    ELSE DATEPART(yyyy,Birthdate) END as [BDate]
    ,ROW_NUMBER() OVER (ORDER BY lastname +' '+ firstname) AS rn FROM ADR_Address 
) as s
PIVOT
(
    MAX(name)
    FOR [BDate] IN ([1930],[1940],[1950],[1960],[1970],[1980],[1990],[2000])
)AS pvt
WHERE Birthdate IS NOT NULL ORDER BY Birthdate

答案 1 :(得分:0)

只需更改查询的这一部分:

SELECT  lastname +' '+ firstname as name,
        Birthdate,
        ...

关于这个:

SELECT  lastname +' '+ firstname as name,
        Birthdate,
        ROW_NUMBER() OVER (ORDER BY Birthdate) as rn,
        ...