我有两个简单的列:datetime PayDate
和int Amount
我尝试编写一个查询,将每天的Amount
计数分开,但它不起作用。
SELECT YEAR(PayDate) + '/' + MONTH(PayDate) + '/' + DAY(PayDate) as a,
COUNT(Amount) as b
FROM TABLE1
GROUP BY a,b
感谢您的帮助。
答案 0 :(得分:3)
至少在SQL Server中,您不能在GROUP BY语句中使用别名。你必须重复这个陈述。
伤心,但确实如此。
SELECT YEAR(PayDate) + '/' + MONTH(PayDate) + '/' + DAY(PayDate) as a,
COUNT(Amount) as b
FROM TABLE1
GROUP BY YEAR(PayDate) + '/' + MONTH(PayDate) + '/' + DAY(PayDate),COUNT(Amount)
答案 1 :(得分:2)
你为什么要烦恼所有这些凌乱的字符串连接?如果需要特定输出,请在客户端上格式化。尽可能使用基类型而不是字符串。
SELECT CONVERT(DATE, PayDate) AS a, COUNT(Amount) AS b
FROM dbo.TABLE1
GROUP BY CONVERT(DATE, PayDate);
如果你有一个对齐的复杂表达式,避免重复它的最简单方法是使用子查询或CTE:
SELECT a, COUNT(b) FROM
(SELECT CONVERT(DATE, PayDate) AS a, Amount AS b FROM dbo.TABLE1) AS x
GROUP BY a;
-- or
WITH x(a,b) AS
(SELECT CONVERT(DATE, PayDate), Amount FROM dbo.TABLE1)
SELECT a, COUNT(b) FROM x
GROUP BY a;
(我不知道你为什么要在你的问题中按a和b分组。)
答案 2 :(得分:0)
您无法在GROUP BY
语句中使用别名。而且无需使用GROUP BY Count(Amount)
SELECT YEAR(PayDate) + '/' + MONTH(PayDate) + '/' + DAY(PayDate) as a,
COUNT(Amount) as b
FROM TABLE1
GROUP BY YEAR(PayDate) + '/' + MONTH(PayDate) + '/' + DAY(PayDate)
或者在SQL Server中执行此操作的其他方法:
SELECT Convert(varchar(20),PayDate,111) as a,
COUNT(Amount) as b
FROM TABLE1
GROUP BY Convert(varchar(20),PayDate,111)
答案 3 :(得分:0)
在MySQL上,您还可以使用简单购买日期时间列的日期。在这种情况下,我不知道你为什么要按别名b分组。在大多数情况下,您可能还希望按日期值排序。
SELECT DATE(PayDate) as a, COUNT(Amount) as b
FROM TABLE1
GROUP BY a
ORDER BY a