Sql计算两列的行,其中col1与col2相同

时间:2012-03-16 19:56:36

标签: mysql sql

我在将下两个查询合并为一个方面时突然失去了作用:

SELECT Data1, COUNT(Data1) FROM Table GROUP BY Data1 ORDER BY Data1;
SELECT Data2, COUNT(Data2) FROM Table GROUP BY Data2 ORDER BY Data2;

所以结果如下:

data1 count1 data2 count2
Alpha 22     Alpha 32 
Delta 33     Delta 44

data1 count1 count2
Alpha 22     32 
Delta 33     44

好像我没有足够的知识来完成它。 提前致谢

4 个答案:

答案 0 :(得分:2)

这样的东西?

SELECT * FROM
  (SELECT Data1, COUNT(Data1) FROM Table GROUP BY Data1) d1
  JOIN (SELECT Data2, COUNT(Data2) FROM Table GROUP BY Data2 ORDER BY Data2) d2
    ON d1.Data1 = d2.Data2
  ORDER BY d1.Data1;

答案 1 :(得分:0)

试试这个:

SELECT t1.Data1, t1.Count1, t1.Data2, t1.Count2 
FROM (SELECT Data1, COUNT(Data1) as Count1 FROM Table GROUP BY Data1) t1,
FROM (SELECT Data2, COUNT(Data2) AS Count2 FROM Table GROUP BY Data2) t2
WHERE t1.Data1 = t1.Data2
ORDER BY t1.Data1

答案 2 :(得分:0)

我想到的最快(但可能不是最好的)解决方案如下所示

(Select "Data1", Data1 As DataSource1, Count(data1) As Count from mytable Group by data1)
Union 
(Select "Data2", Data2 As DataSource2, Count(data2) As Count from mytable group by Data2);

尝试一下,它比连接效率更高。希望它能很好地满足您的需求。

答案 3 :(得分:0)

虽然更多的数据澄清而不是答案...它的声音就像Alpha或Delta的“Data1”列中只有一个值,而且“Data2”还有Alpha或Delta?并且您只想要显示该值出现的每个第一个或第二个位置的总计?

such as 
Data1   Data2
Alpha   Alpha
Alpha   Delta
Alpha   Delta
Delta   Alpha

with a result of 
Alpha  3    2
Delta  1    2

虽然提供的其他查询确实提供了解决方案,但我想知道你是否确实拥有更多的值而不仅仅是两个,并且根据相应列中可能更多的数据值需要更多的行。

如果其他答案没有提供您最终想要的内容,请您确认。