我正在尝试计算2009年各州出售的自行车数量。这来自RollingThunder数据库。这是我的代码:
SELECT
Bicycle.OrderDate,
States.StateName
FROM
Bicycle,
States
WHERE
Bicycle.OrderDate = '2009'
SELECT COUNT(Bicycle.OrderDate) FROM Bicycle;
然而,我的结果很长,没有给我一些自行车。我做错了什么?
答案 0 :(得分:2)
我在这里猜测一些列名(并且Orders在名为Bicycle的表中似乎很奇怪),但它会是这样的:
SELECT
States.StateName,
Count(1) AS Cnt
FROM Bicycle
LEFT JOIN States
ON Bicycle.StateCode = States.StateCode
WHERE Year(Bicycle.OrderDate) = 2009
GROUP BY States.StateName
ORDER BY States.StateName
答案 1 :(得分:0)
我相信您的代码应如下所示:
SELECT COUNT(Bicycle.OrderDate) FROM Bicycle WHERE Bicycle.OrderDate = '2009' GROUP BY Bicycle.OrderDate
答案 2 :(得分:0)
据我了解你想要的是什么,因为最终输出是2009年每个州销售的自行车数量。
试试这个(假设OrderDate属于DATE类型),
SELECT DISTINCT(S.StateName),COUNT(B.OrderDate)
FROM Bicycle B,States S
WHERE B.OrderDate>='2009/01/01' and B.OrderDate<='2009/12/31' and S.<columnName>=B.<columnName>
GROUP BY S.StateName
注意:指定连接两个表的列名,即外键(S.<columnName>=B.<columnName>
),否则您将无法获得所需的输出