2011-03-14 69 views
3

我试图在一个SQL查询中收集统计数据,以方便日期在联合中自动排序。它实际上只有一个表格,但我想要统计不同的数据。MySQL - 联盟还是加入?

我的表看起来是这样的:

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 

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

谢谢!

+0

你应该避免在你的字段名称中使用MySQL关键字(我的意思是“In”字段)。关于问题:不可能以某种方式使用“GROUP BY”? – galymzhan 2011-03-14 15:06:55

+0

嗯,名字实际上是'CheckIn',表格比我在这里展示的要复杂得多,我在我的例子中缩短了它。 – 2011-03-16 00:34:25

回答

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 
+0

实际上,当玩弄一下时,您的解决方案是最灵活的解决方案,而且我无需理解t语法就可以理解它:DI设法为您的应用程序添加更多高级选项模型。 – 2011-03-14 15:56:07

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 
+0

我会'使用(N)'而不是'ON a.n = b.n'。 – Romain 2011-03-14 15:04:23

+0

@Romain,我不喜欢那种方法,我用一个更简单,单一的,没有子查询的解决方案添加到我的答案中 – CaffGeek 2011-03-14 15:12:49

+0

+ 1v谢谢!它充当魅力!我使用USING(n)版本(来自Romain)而不是ON a.n = b.n.现在我会坐下来分析你做了什么,这样我可以学习这是如何工作的:) – 2011-03-14 15:18:01

1

你会使用一个LEFT JOIN使用n场得到,你有东西的日期......那么你最好UNION这与查询,让您在那里没有什么(你给的信息行以上不允许我帮助这将是什么查询:D)。

+0

对于USING(n)建议:) +1 – 2011-03-14 15:18:52