SQL格式输出

时间:2015-06-17 07:09:35

标签: mysql sql

有人可以指导我将下面的SQL查询格式化为以下格式打印吗?

------------------------
COUNT_NAME | COUNT_VAL |
------------------------
COUNT_A    | 1         | 
COUNT_B    | 2         |  
COUNT_C    | 3         |  
COUNT_D    | 4         |
------------------------

以下查询以下列格式返回输出

--------------------------------
COUNT_A|COUNT_B|COUNT_C|COUNT_D|
--------------------------------
1      |2      |3      |4
--------------------------------

SQL QUERY

SELECT t1.COUNT_A, 
       t2.COUNT_B,
       t3.COUNT_C,
       t4.COUNT_D 
FROM
   (SELECT COUNT(INS_NAME) as COUNT_A 
    from table_A 
    where INS_NAME IN 
           (SELECT INS_NAME 
            from table_B 
            WHERE INS_ID IN 
                 (SELECT INS_MAP_ID 
                  FROM TEN_TO_INST_MAP 
                  where T_IN_MAP_ID = 
                     (SELECT T_ID 
                      FROM TW 
                      WHERE TNAM = 'abc')
                  )
            ) 
   AND T_DATE between '2015-01-01' and '2015-07-01' 
   AND INS_NAME NOT LIKE 'x%pr%' 
   AND INS_NAME like 'x%y%' 
   AND INS_NAME not like 'x%y%z') t1
,
(SELECT COUNT(INS_NAME) as COUNT_B 
 from table_A 
 where INS_NAME IN 
             (SELECT INS_NAME 
              from table_B 
              WHERE INS_ID IN 
                 (SELECT INS_MAP_ID 
                  FROM T_IN_MAP 
                  where T_IN_MAP_ID = (SELECT T_ID 
                                       FROM TW WHERE TNAM = 'abc')
                 )
             ) 
    AND T_DATE between '2015-01-01' and '2015-07-01' 
    AND INS_NAME NOT LIKE 'x%pr%' 
    AND INS_NAME like 'x%as%') t2
,
(SELECT COUNT(INS_NAME) as COUNT_C 
 from table_A 
 where INS_NAME IN 
      (SELECT INS_NAME 
       from table_B 
       WHERE INS_ID IN 
            (SELECT INS_MAP_ID 
             FROM T_IN_MAP 
             where T_IN_MAP_ID = (SELECT T_ID 
                                  FROM TW 
                                  WHERE TNAM = 'abc')
            )
       ) 
 AND T_DATE between '2015-01-01' and '2015-07-01' 
 AND INS_NAME NOT LIKE 'x%pr%' 
 AND INS_NAME like 'x%dfg%') t3
,
(SELECT COUNT(INS_NAME) as COUNT_C 
 from table_A 
 where INS_NAME IN 
           (SELECT INS_NAME 
            from table_B 
            WHERE INS_ID IN 
                (SELECT INS_MAP_ID 
                 FROM T_IN_MAP 
                 where T_IN_MAP_ID = (SELECT T_ID 
                                      FROM TW 
                                      WHERE TNAM = 'abc')
                )
            ) 
    AND T_DATE between '2015-01-01' and '2015-07-01' 
    AND INS_NAME NOT LIKE 'x%pr%' 
    AND INS_NAME like 'x%y%z') t4

1 个答案:

答案 0 :(得分:1)

我相信您需要一个Pivot来将行数据转换为列。 这个主题几乎正是您所需要的: MySQL pivot table