SQL Group通过减少三个表的行

时间:2016-09-13 08:26:06

标签: mysql sql

我有三个表,我希望将它们组合起来并减少冗余信息。

我的表目前看起来像这样。 所有表格都包含日期,ID和计数值。

date_a  | id_a | count_a |date_b    | id_b | count_b | date_c   | id_c |count_c
2016.08 | 1    | 3       | 2016.08  | 3    | 135     | 2016.08  | 1    | 11
2016.08 | 2    | 21      | 2016.08  | 3    | 135     | 2016.08  | 3    | 19
2016.08 | 2    | 21      | 2016.08  | 2    | 1       | 2016.08  | 1    | 11
2016.08 | 2    | 21      | 2016.08  | 3    | 135     | 2016.08  | 1    | 11
2016.08 | 1    | 3       | 2016.08  | 2    | 1       | 2016.08  | 2    | 103
2016.08 | 2    | 21      | 2016.08  | 2    | 1       | 2016.08  | 2    | 103
2016.08 | 1    | 3       | 2016.08  | 3    | 135     | 2016.08  | 2    | 103
2016.08 | 2    | 21      | 2016.08  | 3    | 135     | 2016.08  | 2    | 103
2016.08 | 1    | 3       | 2016.08  | 2    | 1       | 2016.08  | 3    | 19
2016.08 | 2    | 21      | 2016.08  | 2    | 1       | 2016.08  | 3    | 19
2016.08 | 1    | 3       | 2016.08  | 3    | 135     | 2016.08  | 3    | 19
2016.08 | 1    | 3       | 2016.08  | 2    | 1       | 2016.08  | 1    | 11

但我想要的只是这个。 (也许没有多个日期?)

EDID 刚看到表C有三个值。有可能展示这样的东西吗?表A或表B可能具有相同的行为。

date_a | id_a | count_a |date_b | id_b | count_b | date_c | id_c |count_c 2016.08 | 1 | 3 | 2016.08 | 3 | 135 | 2016.08 | 3 | 19 2016.08 | 2 | 21 | 2016.08 | 2 | 1 | 2016.08 | 1 | 11 | | | | | | 2016.08 | 2 | 103

只需要组合每个表的值。因此id_Xcount_X需要位于同一行。 X代表a,b或c。这意味着id_a和count_a(1和3)需要位于同一行,但id_acount_aid_b和{{1}位于同一行并不重要}}。 count_bid_c同样如此。

我当前的SQL语句如下所示。

count_c

我尝试了多个分组,但无法获得所需的表格。

2 个答案:

答案 0 :(得分:0)

只是单挑,我对mysql相当生疏,我没有测试过SQL,但设计应该是有效的。 我会说你开始使用低于预期的结果格式。垂直排列结果将减少很多复杂性,但仍然可读。 union(不是union all)应该合并所有重复的记录。

date   |TableName|id|counter
2016-09|   A     |3 | 20
2016-09|   B     |1 | 13
2016-09|   B     |5 | 1
2016-10|   A     |3 | 7

select *
from (
    select date, 'A' as 'TableName', id, counter from Table_a
    union 
    select date, 'B' as 'TableName', id, counter from Table_b
    union 
    select date, 'C' as 'TableName', id, counter from Table_c
) tmp
order by date, TableName, id, counter

答案 1 :(得分:0)

如果你真的想要回答你的问题:

SET @rank_a=0;
SET @rank_b=0;
SET @rank_c=0;

SELECT
  a.date as DateA,
  a.id as IdA,
  a.counter as Count_Erstellt as CounterA,
  b.date as DateB,
  b.id as Anforderung_Geschlossen as IdB,
  b.counter as CounterB,
  c.date as DateA,
  c.id as Anforderung_Changed as IdA,
  c.counter as CounterA
FROM (SELECT @rank_c:=@rank_c+1 as tmp_id, id, counter, date FROM TableC) AS c
  LEFT JOIN (select @rank_b:=@rank_b+1 as tmp_id, id, counter, date from TableB) AS b
   ON c.tmp_id = b.tmp_id
 LEFT JOIN (select @rank_a:=@rank_a+1 as tmp_id, id, counter, date from TableA) AS a
   ON c.tmp_id = a.tmp_id;

但要注意两件事:

  • 具有最大结果集的表应该是第一个表(或者您需要进行正确的连接)
  • 这个查询的实用性在我们的范围内,比方说,是不切实际的。也许您可以使用一些编程语言来解决您的问题
每次运行查询时都不要忘记SET @ rank_ *;