Sql:在单行而不是不同的列中显示数据

时间:2015-11-03 07:56:27

标签: mysql sql

我写了一个sql查询,如下所示

SELECT ryot_code, ryot_name, variety_group, SUM(total_area)
FROM field_survey_trn
WHERE unit_code = '01'
  AND season_cntrl = 20
  AND crop_type_code NOT IN (11,12)
  AND ryot_code != 0
GROUP BY ryot_code, ryot_name, variety_group;

输出

enter image description here

variety_group 列中,我在不同的行中获得了相同ryot_code的不同品种代码。

我的问题是,我如何编写一个查询,使用该查询可以获得所有类型或** variety_code **,用于同一个种植者,如下图所示

enter image description here

3 个答案:

答案 0 :(得分:1)

我在原始问题中将查询包装在外部查询中,该查询在variety_group列上执行了一个数据透视:

SELECT t.ryot_code, t.ryot_name,
    SUM(CASE WHEN t.variety_group = 10 THEN t.theSum ELSE 0 END) AS '10',
    SUM(CASE WHEN t.variety_group = 20 THEN t.theSum ELSE 0 END) AS '20',
    SUM(CASE WHEN t.variety_group = 30 THEN t.theSum ELSE 0 END) AS '30'
FROM
(
    SELECT ryot_code, ryot_name, variety_group, SUM(total_area) AS theSum
    FROM field_survey_trn
    WHERE unit_code = '01' AND season_cntrl = 20
        AND crop_type_code NOT IN (11,12) AND ryot_code != 0
    GROUP BY ryot_code, ryot_name, variety_group
) t
GROUP BY t.ryot_code, t.ryot_name

答案 1 :(得分:1)

您可以使用PIVOT在SQL中执行此操作。

SELECT * FROM

(
   SELECT ryot_code, ryot_name, variety_group, total_area
FROM field_survey_trn
WHERE unit_code = '01'
  AND season_cntrl = 20
  AND crop_type_code NOT IN (11,12)
  AND ryot_code != 0

) as my_name

PIVOT

(

    SUM(total_area)

    FOR [variety_group] IN ([10], [20], [30])
) piv1;

答案 2 :(得分:0)

而不是结果 如果你在多样化组的单列中设计它,并使用逗号分隔值(例如10,30) ryot_code 00010004

如果您喜欢该建议,则可以使用以下查询

完成
`SELECT group_concat(variety_group separator ',') INTO var_grp, 
    ryot_code, ryot_name, SUM(total_area)
 FROM field_survey_trn
 WHERE unit_code = '01'
 AND season_cntrl = 20
 AND crop_type_code NOT IN (11,12)
 AND ryot_code != 0;`

希望这可以按预期工作