如何将SQL / MySQL查询输出分成多个表?

时间:2015-03-13 13:10:54

标签: mysql sql

我有以下查询:

SELECT  COUNT (*) AS Total, Program, Status
FROM APP_PGM_CHOICE
WHERE Program IN ( 'EX', 'IM')
AND  APP_PGM_REQ_DT  >= '20150101'
AND APP_PGM_REQ_DT  <= '20150131'
AND Status IN ( 'PE','DN','AP')
GROUP BY  Program, Status
ORDER BY  Program, Status

输出是:

Total   Program   Status
12246   "EX"      "AP"
13963   "EX"      "DN"
21317   "EX"      "PE"
540     "IM"      "AP"
2110    "IM"      "DN"
7184    "IM"      "PE"

我希望输出如下:

Total1  Program1   Total2   Program2  Status
12246     EX        540       IM        AP
13963     EX        2110      IM        DN
21317     EX        7184      IM        PE

我可以做ii吗?如果是的话怎么样?

3 个答案:

答案 0 :(得分:1)

您可以使用UNION查询和一些简单的选择

来执行此操作
SELECT GROUP_CONCAT(total1) as total1, GROUP_CONCAT(proram1) as program1, GROUP_CONCAT(total2) as total2, GROUP_CONCAT(program2) as program2
FROM 
(SELECT total AS total1, program AS program1, null AS total2, null AS program2
WHERE program = 'EX'
UNION
SELECT null AS total1, null AS program1, total AS total2, program AS program2
WHERE program = 'IM') t

这是将行转移到列

的简便方法

答案 1 :(得分:1)

是的,你可以这样做:

Select T1.Total Total1, T1.Program Program1, T2.Total Total2, T2.Program Program2, T1.Status

From
(SELECT  COUNT (*) AS Total, Program, Status
FROM APP_PGM_CHOICE
WHERE Program = 'EX'
AND  APP_PGM_REQ_DT  >= '20150101'
AND APP_PGM_REQ_DT  <= '20150131'
AND Status IN ( 'PE','DN','AP')
GROUP BY  Program, Status
ORDER BY  Program, Status) T1

INNER JOIN

(SELECT  COUNT (*) AS Total, Program, Status
FROM APP_PGM_CHOICE
WHERE Program = 'IM'
AND  APP_PGM_REQ_DT  >= '20150101'
AND APP_PGM_REQ_DT  <= '20150131'
AND Status IN ( 'PE','DN','AP')
GROUP BY  Program, Status
ORDER BY  Program, Status) T2 on T1.Status = T2.Status

答案 2 :(得分:0)

在sql Temp Table中非常实用且易于使用..

轻松获得输出。

选择总计,程序,状态 进入#TempAA 来自CGT Prog ='EX'的地方 按状态分组,总计,程序

选择总计,程序,状态 进入#TempBB 来自CGT Prog ='IM'的地方 按状态分组,总计,程序

选择A.Total为[Total1],A.Prog为[Program1],B.Total为[Total2],B.Prog为[Program2],A.Status 来自#TempAA A. 内连接#TempBB B on b.Status = A.status