将行值显示为要在网格视图中显示的列

时间:2013-12-31 06:27:29

标签: mysql sql select group-by sum

我有一个Mysql数据库,其中一个表有两列Department,并处理为:

Department | deals 
HR         | A1  
Sales      | A2 
Revenue    | A1 
HR         | A3  

我想在asp.net gridview中显示数据:

         A1| A2 | A3 
HR       1    0    1
Sales    0    1    0
Revenue  1    0    0

我怎样才能做同样的事情,因为未知或已修复交易中的值。 我在下面使用,但它没有显示所需的输出

SELECT GROUP_CONCAT(CONVERT(deals,char(10)))
FROM Table1
group by Department

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT Department, 
       SUM(deals='A1') AS A1, 
       SUM(deals='A2') AS A2, 
       SUM(deals='A3') AS A3
FROM Table1
GROUP BY Department

Dynamic Deals

SELECT GROUP_CONCAT(DISTINCT CONCAT("SUM(deals='", deals, "') AS '", deals, "'")) INTO @temp
FROM Table1;

SET @sql = CONCAT('SELECT Department, ', @temp, 'FROM Table1 GROUP BY Department');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SELECT Department, 
       SUM(IF(deals='A1', 1, 0)) AS A1, 
       SUM(IF(deals='A2', 1, 0)) AS A2, 
       SUM(IF(deals='A3', 1, 0)) AS A3
FROM Table1
GROUP BY Department;

Dynamic Deals

SELECT GROUP_CONCAT(DISTINCT CONCAT("SUM(IF(deals='", deals, "', 1, 0)) AS '", deals, "'")) INTO @temp
FROM Table1;

SET @sql = CONCAT('SELECT Department, ', @temp, 'FROM Table1 GROUP BY Department');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;