使用SQL在一个表中连接两个表

时间:2016-09-27 19:38:18

标签: mysql sql

晚上好,

我在尝试找到加入两个表的解决方案时遇到了问题:

例如我有

表1:

Date  | Item
12/03 | aaaa
12/03 | aaaa
14/03 | bbbb
14/03 | aaaa
15/03 | cccc

表2:

Date  | Item2
11/03 | aaaa
12/03 | aaaa
13/03 | bbbb
14/03 | aaaa
15/03 | cccc   

我想要计算这个

Date  | Count(Item1) | Count(Item2)
11/03 | 0            | 1
12/03 | 2            | 1
13/03 | 0            | 1
14/03 | 2            | 1
15/03 | 1            | 1

到目前为止,我已经尝试了这个,但它似乎没有用,它只给了我公共日期:

SELECT F.DATE, COUNT(T1.Item1), COUNT(T2.Item2) FROM TABLE1 
T1 LEFT JOIN TABLE2 T2 ON T1.date=T2.date

Date  | Count(Item1) | Count(Item2)
12/03 | 2            | 1
14/03 | 2            | 1
15/03 | 1            | 1

有任何帮助吗?

由于

2 个答案:

答案 0 :(得分:3)

In the below SQL, the first inline view is computing all the counts at date level and same applies with second query. By combining the results of left join and right join between these two inline views we can combine all the common and uncommon results from both tables as you described.


        SELECT Date,
               Item1,
               Item2 
          FROM
             (  
                SELECT T1.Date AS Date,
                       COUNT(  T1.Item  ) AS Item1,                     
                       COUNT(  T2.Item  ) AS Item2  
                  FROM Table1 t1
                LEFT JOIN
                       Table2 t2  
                    ON t1.date = t2.date  
                GROUP BY t1.Date              
          UNION              
                SELECT T2.Date AS Date,
                       COUNT( T1.Item ) AS Item1,
                       COUNT( T2.Item ) AS Item2
                  FROM Table2 t2
                LEFT JOIN
                       Table1 t1   
                    ON t2.date = t1.date
                GROUP BY t2.Date
              ) A
         ORDER BY Date        
        ;

SQL小提琴实施: -

http://sqlfiddle.com/#!9/5b872/14

答案 1 :(得分:0)

我认为这就是您所需要的 - 您使用计数对日期中的每个表进行分组,然后从两个分组表中添加值:

DECLARE @tab1 TABLE
(
    [Date] VARCHAR(5),
    Item1 VARCHAR(100)
)

DECLARE @tab2 TABLE
(
    [Date] VARCHAR(5),
    Item2 VARCHAR(100)
)

INSERT INTO @tab1 ( Date, Item1 ) VALUES 
('12/03','aaaa'),
('12/03','aaaa'),
('14/03','bbbb'),
('14/03','aaaa'),
('15/03','cccc')

INSERT INTO @tab2 ( Date, Item2 ) VALUES 
('11/03','aaaa'),
('12/03','aaaa'),
('13/03','bbbb'),
('14/03','aaaa'),
('15/03','cccc')


;WITH grp AS (
SELECT [Date],COUNT(*) AS Item1, 0 AS Item2 FROM @tab1 
GROUP BY [Date]

UNION

SELECT [Date],0, COUNT(*) FROM @tab2 
GROUP BY [Date] )

SELECT grp.Date, SUM(grp.Item1) AS [CountItem1], SUM(grp.Item2) AS [CountItem2] FROM grp
GROUP BY grp.Date