对如何查询此表感到困惑

时间:2013-04-10 18:26:40

标签: mysql

我有两个简单的表格设置:

table: deals
dealID   |   dealDate    | storeName
1        |   2013-04-01  | bayport
2        |   2013-04-01  | staten island
3        |   2013-04-04  | bayport



table: phoneDetails
phoneID    |   dealID    | dateReceived
1          |   1         | 2013-04-04
2          |   1         | 2013-04-04
3          |   2         | 2013-04-06
4          |   3         | 2013-04-05
5          |   3         | 2013-04-05

因此,基于此表,我需要查询我的数据库以显示dealDate以及每个商店在该日期收到的手机数量,或者甚至使用日历日期而不是dealDate也可以。例如:

dealDate    |  storeName     | Received
2013-04-01  |  bayport       | 0
2013-04-01  |  staten island | 0
2013-04-04  |  bayport       | 2

任何帮助将不胜感激。我知道如何查询dealDate和storeName但我很困惑如何查询'Received'计数因为dealDate和dateReceived不同。

@echo_me,如何将结果更改为基于日历而不是dealDate的结果。看看我是如何在4月6日收到1部电话的,尽管那天没有完成交易

date       |  storeName      |  received
2013-04-01 |                 |  0
2013-04-02 |         |                          
2013-04-03 |                 |
2013-04-04 | bayport         |  2
2013-04-05 | bayport         |  1
2013-04-06 | staten island   |  1 

3 个答案:

答案 0 :(得分:1)

我认为这会在你的例子中产生结果:

select d.dealDate dealDate, storeName, ifnull(count(*), 0) Received
from deals d
left join phoneDetails p on d.dealId = p.dealId and d.dealDate = p.dateReceived
group by dealDate, storeName

对于您要求的第二个结果,应该这样做:

select dateReceived date, storeName, count(*) received
from phoneDetails p
join deals using (dealId)
group by date, storeName
order by date

这不会显示没有收到任何内容的日子,您需要加入一个包含您关注范围内所有日期的表,并且在MySQL中没有内置方法可以做到这一点(我认为SQL-服务器或Oracle可以做到这一点)。有关填写包含所有日期的临时表的方法,请参阅this question,然后您可以使用上述查询将其连接起来,以生成您想要的0行。

答案 1 :(得分:1)

试试这个

SELECT a.dealDate as dealDate, a.storeName as storeName, count(dateReceived) as Received
FROM deals a 
LEFT JOIN phoneDetails b 
ON a.dealDate = b.dateReceived
GROUP BY dealDate, storeName

DEMO HERE

答案 2 :(得分:0)

如果您尝试以下内容,则会返回收到日期晚于交易日期的计数。

select a.dealDate as dealDate, a.storeName as storeName, b.dateReceived as dateReceived,  count(*) as counts
  from deals a left outer join phoneDetails b on a.dealId = b.dealId
 where b.dateReceived >= a.dealDate
 group by dealDate, storeName, dateReceived

这能满足您的需求吗?