Sql只从一个表连接

时间:2012-02-11 13:08:58

标签: mysql sql

我需要一些查询设计方面的帮助。 我有一个有很多行的表(它需要在一个表中)。

Table name: 201201
columns = code, batch, value, volume
rows =    301,  2920,  100,   2000
          301,  3192,  40,    800
          302,  6479,  230,   3100
          303,  4930,  20,    50
          303,  3920,  60,    95

我怎样才能拉出结果,以便以这种方式呈现:

code, batches, value, volume
301,  2,       140,   2800
302,  1,       230,   3100
303,  2,       80,    145

我在使用multiplie表时已经这样做了,但是当所有行都在同一个表中时无法使它工作。

我设法通过此查询获取批次计数和mrdr

SELECT DISTINCT(`201201`.code), count(DISTINCT(z.batch)) as batches
FROM `201201` 
LEFT JOIN `201201` AS z ON `201201`.code = z.code
GROUP BY `201201`.code

但后来我被困住了。 提前谢谢。

新问题! 好的,所以在同一个表中我有一个风险列,其中包含每个批次的浮点数:

    Table name: 201201
columns = code, batch, value, volume, risk
rows =    301,  2920,  100,   2000,   0.3
          301,  3192,  40,    800,    0.2
          302,  6479,  230,   3100,   0.8
          303,  4930,  20,    50,     0.8
          303,  3920,  60,    95,     1

我想要的是将风险乘以每行的值,然后按照代码求和,就像这样。

code, batches, value, volume, risk
301,  2,       140,   2800,   38

38来自,0.3 * 100 + 0.2 * 40。 代码302和303也是如此。

3 个答案:

答案 0 :(得分:1)

为什么在没有加入的情况下你可以加入?希望这会有所帮助:

SELECT `code`, 
        COUNT(`Batch`) as Batches,
        SUM(`Value`) as TotalValue,
        SUM(`Volume`) as TotalVolume,
        SUM(`Value` * `Risk`) as TotalRisk  -- I'm not sure if this works
FROM `201201`
GROUP BY `code`

如果上述方法不起作用,请尝试自我加入:

SELECT a.`code`, 
        COUNT(a.`Batch`) as Batches,
        SUM(a.`Value`) as TotalValue,
        SUM(a.`Volume`) as TotalVolume,
        SUM(b.`SubRisk`) as TotalRisk
FROM `201201` a INNER JOIN 
            (
                SELECT c.`code`, (c.`Value` * c.`Risk`) as SubRisk
                FROM `201201` c
            ) b ON a.`Code` = b.`Code`
GROUP BY `code`

答案 1 :(得分:0)

看起来你正在添加其他值..?

SELECT code, count(batch) as batches, sum(value) as values, sum(volume ) as volumes
FROM `201201` 
GROUP BY `201201`.code

答案 2 :(得分:0)

SELECT Code, Count(Batch), Sum(Value), Sum(Count) FROM 201201 GROUP BY Code