0

我有一个包含以下字段和示例数据的 SQL Server 表:

用户表

ID         Name   Address
23052-PF   Peter  Timbuktu
23052-D1   Jane   Paris
23052-D2   David  London
23050-PF   Sam    Beijing
23051-PF   Nancy  NYC
23051-D1   Carson Cali
23056-PF   Grace  LA

年龄表

ID         Age
23052-PF   25
23052-D1   22
23052-D2   25
23050-PF   22
23051-PF   26
23051-D1   22
23056-PF   28

我需要在单独的列中返回 ID、姓名、地址、年龄和年龄列的出现次数。

该表需要根据年龄列的计数进行降序排序。

上述示例数据的输出需要如下所示:

ID         Name   Address   Age  Age(Count)
23052-PF   Peter  Timbuktu  25   3
23056-PF   Grace  LA        25   3
23051-D1   Carson Cali      25   3
23052-D1   Jane   Paris     22   2
23050-PF   Sam    Beijing   22   2
23052-D2   David  London    24   1
23051-PF   Nancy  NYC       26   1

感谢你的帮助!

4

2 回答 2

3

Here is another approach:

select u.id, u.name, u.address, a.age, count(*) over (partition by ages) as "Age(Count)"
from users u join
     ages a
     on u.id = a.id
order by "Age(Count)" desc

You can also use:

order by 4 desc

although use of column numbers in order by is discouraged.

于 2013-09-06T01:03:58.467 回答
3

这应该可以得到你想要的。

CREATE TABLE #u
(
    id          nvarchar(100),
    Name        nvarchar(100),
    Address     nvarchar(100)
)

INSERT INTO #u
SELECT N'23052-PF', N'Peter',  N'Timbuktu' UNION
SELECT N'23052-D1', N'Jane',   N'Paris'    UNION
SELECT N'23052-D2', N'David',  N'London'   UNION
SELECT N'23050-PF', N'Sam',    N' Beijing' UNION
SELECT N'23051-PF', N'Nancy',  N'NYC'      UNION
SELECT N'23051-D1', N'Carson', N'Cali'     UNION
SELECT N'23056-PF', N'Grace',  N'LA'

CREATE TABLE #a
(
    id          nvarchar(100),
    Age         int
)

INSERT INTO #a
SELECT N'23052-PF', 25 UNION
SELECT N'23052-D1', 22 UNION
SELECT N'23052-D2', 25 UNION
SELECT N'23050-PF', 22 UNION
SELECT N'23051-PF', 26 UNION
SELECT N'23051-D1', 22 UNION
SELECT N'23056-PF', 28

;WITH
cte AS
(
    SELECT
        u.id,
        u.Name,
        u.Address,
        a.Age,
        COUNT(*) OVER (PARTITION BY a.Age) AS [Age(Count)]
    FROM
        #u AS u INNER JOIN #a AS a
            ON
                u.id = a.id
)
SELECT
    *
FROM
    cte
ORDER BY
    [Age(Count)] DESC
于 2013-09-05T23:50:31.623 回答