我有两个简单的列:
我尝试编写一个单独计算每天的查询,datetime PayDate
但它不起作用。int Amount
Amount
SELECT YEAR(PayDate) + '/' + MONTH(PayDate) + '/' + DAY(PayDate) as a,
COUNT(Amount) as b
FROM TABLE1
GROUP BY a,b
谢谢你的帮助。
我有两个简单的列:
我尝试编写一个单独计算每天的查询,datetime PayDate
但它不起作用。int Amount
Amount
SELECT YEAR(PayDate) + '/' + MONTH(PayDate) + '/' + DAY(PayDate) as a,
COUNT(Amount) as b
FROM TABLE1
GROUP BY a,b
谢谢你的帮助。
至少在 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)
你为什么要为所有这些凌乱的字符串连接而烦恼?如果您想要特定的输出,请在客户端上格式化。尽可能使用基本类型而不是字符串。
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 分组。)
您不能在语句中使用别名。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)
请参阅投射和转换
在 MySQL 上,您还可以简单地使用购买来获取 datetime 列的日期。我不知道为什么在这种情况下你会按别名 b 分组。在大多数情况下,您可能还想按日期值排序。
SELECT DATE(PayDate) as a, COUNT(Amount) as b
FROM TABLE1
GROUP BY a
ORDER BY a