MySQL - 联盟还是加盟?

时间:2011-03-14 14:58:11

标签: mysql join union

我正在尝试在一个SQL查询中收集统计数据,以方便在联合中自动排序日期。它实际上只有一个表,但我想计算不同的数据情况。

我看到的表格如下:

ID   In          Wanted
441  2011-03-14  0
439  2011-03-14  1
442  2011-03-14  0
428  2011-03-13  1
431  2011-03-13  1
425  2011-03-11  0
423  2011-03-11  1
420  2011-03-09  1

我接近这个查询所需的结果:

SELECT * FROM
(
  (SELECT date(In) n, count(date(In)) cntw, null cntl FROM items i WHERE Wanted=1 group by date(In))
union all
  (SELECT date(In) n, null cntw, count(date(In)) cntl FROM items i WHERE Wanted=0 group by date(In))
) Serie
Order by n DESC

但是关闭不够接近:D我得到的结果是:

n            cntw   cntl
2011-03-14   null   2
2011-03-14   1      null
2011-03-13   2      null
2011-03-11   null   1
2011-03-11   1      null
2011-03-09   1      null

我想要的是按日期在同一行“混合”结果:

n            cntw   cntl
2011-03-14   1      2
2011-03-13   2      null
2011-03-11   1      1
2011-03-09   1      null

正如您所看到的,每个日期只有一行。 实际上最完美的结果就是在那里甚至还有丢失的日期:

n            cntw   cntl
2011-03-14   1      2
2011-03-13   2      null
2011-03-12   null   null
2011-03-11   1      1
2011-03-10   null   null
2011-03-09   1      null

......但我想这是不可能的。

谢谢!

3 个答案:

答案 0 :(得分:3)

select date(In) as n,
       sum(case when wanted = 1 then 1 else 0 end) as cntw,
       sum(case when wanted = 0 then 1 else 0 end) as cntl
    from items
    group by date(In)
    order by n desc

答案 1 :(得分:1)

你想加入他们,我想这会有用

SELECT * FROM
  (SELECT date(In) n, count(date(In)) cntw, null cntl FROM items i WHERE Wanted=1 group by date(In)) as a
LEFT JOIN
  (SELECT date(In) n, null cntw, count(date(In)) cntl FROM items i WHERE Wanted=0 group by date(In)) as b
ON a.n = b.n
Order by n DESC

但我认为这可以在一个查询中完成,也许这样吗?

CREATE TABLE #tmpFoo (
    SomeDate datetime,
    Wanted bit
)

INSERT INTO #tmpFoo VALUES ('2011-03-11', 0)
INSERT INTO #tmpFoo VALUES ('2011-03-11', 1)
INSERT INTO #tmpFoo VALUES ('2011-03-12', 0)
INSERT INTO #tmpFoo VALUES ('2011-03-12', 1)
INSERT INTO #tmpFoo VALUES ('2011-03-14', 0)

SELECT  SomeDate n, 
        count(NULLIF(Wanted,0)) cntw, 
        count(NULLIF(Wanted,1)) cntl 
    FROM #tmpFoo i  
    GROUP BY SomeDate

答案 2 :(得分:1)

您使用LEFT JOIN使用n字段来获取您拥有内容的日期...然后您UNION使用查询为您提供这些内容什么都没有(你上面给出的信息不允许我帮助查询这个问题:D)。

相关问题