从行

时间:2019-04-08 20:45:17

标签: sql-server tsql

我正在处理查询,但是我不知道如何执行特定操作。 我有一张表格,可以根据他们的所在地区,年龄和他们的四项活动选择个人。

所以我要选择按地区,平均年龄和所有活动的总和分组的个人。目的是从中选择主要活动 4.对于一个区域。这样我的数据就返回了

region  number   avgage   a1   a2  a3   a4  needed?
----------------------------------------------------
A        5       45       3    4    1   5     a4
B        4       23       1    8    2   6     a2

SQL

SELECT 
    C.gri,COUNT(A.ID) AS num,
    AVG(CONVERT(INT, ROUND(DATEDIFF(HOUR, dob, GETDATE()) / 8766.0, 0))) AS AveAge,
    SUM(CASE WHEN gender = 'male' THEN 1 ELSE 0 END) AS Male,
    SUM(CASE WHEN gender = 'female' THEN 1 ELSE 0 END) AS Female,
    SUM(CAST(a1 AS INT)) AS a1,
    SUM(CAST(a2 AS INT)) AS a2,
    SUM(CAST(a3 AS INT)) AS a3,
    SUM(CAST(a4 AS INT)) AS a4,
FROM
    profiile A
INNER JOIN 
    city B ON A.city = B.id
INNER JOIN 
    region C ON B.gri = C.id
GROUP BY 
    C.gri

我要完成的工作是检索needed列的方法。

感谢可以提供的任何帮助。

2 个答案:

答案 0 :(得分:1)

您可以使用案例声明

CASE
WHEN COALESCE(A1, 0) > COALESCE(A2, 0) AND COALESCE(A1, 0) > COALESCE(A3, 0) AND COALESCE(A1, 0) > COALESCE(A4, 0) THEN 'A1'
WHEN COALESCE(A2, 0) > COALESCE(A3, 0) AND COALESCE(A2, 0) > COALESCE(A4, 0) THEN 'A2'
WHEN COALESCE(A3, 0) > COALESCE(A4, 0) THEN 'A3'
ELSE 'A4' END AS MainActivity

如果您不必担心NULL,那么可以摆脱合并。如果有多个具有相同计数的活动,它将返回具有该最大值的最后一个活动

答案 1 :(得分:0)

尝试这样的事情:

SELECT *, x.ColumnName
FROM YourQuery
CROSS APPLY (
    SELECT TOP 1 ColumnName
    FROM (
        SELECT 'a1' AS ColumnName, a1 AS TheValue
        UNION ALL SELECT 'a2', a2
        UNION ALL SELECT 'a3', a3
        UNION ALL SELECT 'a4', a4
    ) y
    ORDER BY TheValue DESC
) x