分组 - 需要在单行显示

时间:2014-02-06 17:13:08

标签: mysql sql

我有以下架构设置:

表名:thing

Column | type
----------------------------
id     | auto increment int
ident  | int
cost1  | int
cost2  | int
cost3  | int

表名:thing_usage

column     | type
---------------------------------
id         | auto increment int
thing      | int - FK to thing.id
usage_type | int
data       | int
duration   | int

有一些数据:

thing

id    | ident    | cost1    | cost2   | cost3
------------------------------------------------
1     | 1234     | 1        | 2       | 3
2     | 5678     | 0        | 0       | 0

thing_usage

id    | thing     | usage_type  |  data    | duration
--------------------------------------------------------
1     | 1         | 1           | 5555     | 0
2     | 1         | 1           | 3        | 0
3     | 1         | 2           | 0        | 123
4     | 1         | 3           | 232      | 12

此处全部可用 - > SQLFiddle

如果每个thing有一行,我想输出的内容如下:

thing   | cost1   | usage1   | cost2   | usage2   | cost3   | usage3
------------------------------------------------------------------------
1       | 1       | 5558     | 2       | 00:02:03 | 3       | 232
2       | 0       | 0        | 0       | 0        | 0       | 0

cost1使用usage_type 1cost2使用usage_type的{​​{1}}等等......和{{ 1}}和2使用cost1来使用它,cost3data从秒转换为hh:mm:ss用于使用 - 用法应该相加

目前我必须在代码中创建2个查询 - 所以我循环所有cost2行然后获取它的用法并相应地输出

有什么方法可以从单个查询中获得所需的输出 - 可能使用某种子查询?

2 个答案:

答案 0 :(得分:0)

如果您想“手动”执行此操作,可以帮助您入门:

SELECT
th.ident,
th.cost1,
SUM(tu.data) as usage1data
FROM
thing th
JOIN thing_usage tu
ON th.id = tu.thing
WHERE tu.usage_type = 1
GROUP BY th.id, tu.usage_type

这个查询应该让你继续在一个语句中收集所有的总和:

SELECT
tu.thing,
    SUM(CASE WHEN usage_type=1 THEN tu.data ELSE 0 END) AS usage1,
    SUM(CASE WHEN usage_type=2 THEN tu.data ELSE 0 END) AS usage2,
    SUM(CASE WHEN usage_type=3 THEN tu.data ELSE 0 END) AS usage3
FROM 
    thing_usage tu

答案 1 :(得分:0)

希望这就是你要找的东西:

SELECT thing_usage1.id
  ,thing.id
  ,thing.cost1
  ,SUM(thing_usage1.data) AS usage1
  ,thing.cost2
  ,TIME_FORMAT(SEC_TO_TIME(thing_usage2.duration),'%H:%i:%s') AS usage2
  ,thing.cost3
  ,SUM(thing_usage3.data) AS usage3
FROM thing AS thing
INNER JOIN thing_usage AS thing_usage1 ON thing.id = thing_usage1.thing
  AND thing.cost1 = thing_usage1.usage_type
INNER JOIN thing_usage AS thing_usage2 ON thing.id = thing_usage2.thing
  AND thing.cost2 = thing_usage2.usage_type
INNER JOIN thing_usage AS thing_usage3 ON thing.id = thing_usage3.thing
  AND thing.cost3 = thing_usage3.usage_type
GROUP BY thing_usage1.id
  ,thing.id
  ,thing.cost1
  ,thing.cost2
  ,thing.cost3

以下是其工作示例:http://sqlfiddle.com/#!2/68f430/51

更新了我的逻辑以考虑SUM ming篇,以及持续时间的使用。