如何计算SQL中的出现次数
我有一份物品清单(如衬衫、上衣、裤子、阿迪达斯、耐克、彪马等)和年份,格式如下2017-01-01。我想知道每个项目每年购买多少次,并按年度进行安排 我该怎么做 我有一个名为Items的下表:如何计算SQL中的出现次数,sql,group-by,count,aggregate-functions,Sql,Group By,Count,Aggregate Functions,我有一份物品清单(如衬衫、上衣、裤子、阿迪达斯、耐克、彪马等)和年份,格式如下2017-01-01。我想知道每个项目每年购买多少次,并按年度进行安排 我该怎么做 我有一个名为Items的下表: Year | Purchases | ------------------ 2017-01-01 | makeup 2018-01-01 | clothing 2019-01-01 | makeup 2017-01-01 | shoes 2017-01-01 | clothing 2016-01-01
Year | Purchases |
------------------
2017-01-01 | makeup
2018-01-01 | clothing
2019-01-01 | makeup
2017-01-01 | shoes
2017-01-01 | clothing
2016-01-01 | shoes
2018-01-01 | clothing
2017-01-01 | clothing
2019-01-01 | makeup
所需的输出如下所示:
Year | Purchases| Count
-----------------------
2016 | Shoes | 1
2017 | Makeup | 1
2017 | Clothing | 2
2017 | Shoes | 1
2018 | Clothing | 2
2019 | Makeup | 2
到目前为止,我的代码是:
SELECT YEAR(d.date_format) AS Year
, Purchase = (CASE WHEN it.type IN ('shirts', 'tops', 'pants) THEN 'clothing'
WHEN it.type('nike','adidas', 'puma') THEN 'shoes'
WHEN it.type('facewash', 'lipstick') THEN 'makeup' END), COUNT(*)
FROM ....
INNER JOIN...
WHERE...
GROUP BY Year, Purchase
ORDER BY Year
您可以使用
groupby
和orderby
select year, purchases, count(*)
from myTable
group by year, purchases
order by year
您可以使用
groupby
和orderby
select year, purchases, count(*)
from myTable
group by year, purchases
order by year
这是你想要的吗
SELECT YEAR(d.date_format) AS Year,
(CASE WHEN it.type IN ('shirts', 'tops', 'pants') THEN 'clothing'
WHEN it.type IN ('nike','adidas', 'puma') THEN 'shoes'
WHEN it.type IN ('facewash', 'lipstick') THEN 'makeup'
END), COUNT(*)
FROM .... INNER JOIN...
WHERE...
GROUP BY YEAR(d.date_format),
(CASE WHEN it.type IN ('shirts', 'tops', 'pants') THEN 'clothing'
WHEN it.type IN ('nike','adidas', 'puma') THEN 'shoes'
WHEN it.type IN ('facewash', 'lipstick') THEN 'makeup'
END)
ORDER BY Year;
在选择中使用=
表示您正在使用SQL Server。SQL Server不支持在“分组依据”中使用别名,因此您需要重复该表达式。这是您想要的吗
SELECT YEAR(d.date_format) AS Year,
(CASE WHEN it.type IN ('shirts', 'tops', 'pants') THEN 'clothing'
WHEN it.type IN ('nike','adidas', 'puma') THEN 'shoes'
WHEN it.type IN ('facewash', 'lipstick') THEN 'makeup'
END), COUNT(*)
FROM .... INNER JOIN...
WHERE...
GROUP BY YEAR(d.date_format),
(CASE WHEN it.type IN ('shirts', 'tops', 'pants') THEN 'clothing'
WHEN it.type IN ('nike','adidas', 'puma') THEN 'shoes'
WHEN it.type IN ('facewash', 'lipstick') THEN 'makeup'
END)
ORDER BY Year;
在选择中使用=
表示您正在使用SQL Server。SQL Server不支持在分组依据中使用别名,因此您需要重复该表达式。您好!你能查一下我的最新帖子吗?当我尝试进行计数(*)时,我收到一个错误,显示“无效列名'Year'”,而购买列也出现了相同的错误嗨!你能查一下我的最新帖子吗?当我尝试进行计数(*)时,我收到一个错误,显示“无效列名'Year'”,而购买列也出现了相同的错误嗨!你能查一下我的最新帖子吗?当我尝试进行计数(*)时,我收到一个错误,显示“无效列名'Year'”,而购买列也出现了相同的错误嗨!你能查一下我的最新帖子吗?当我尝试进行计数(*)时,我在“无效列名'Year'”和“购买”列中遇到了相同的错误下面给出的答案应该已经有效了,除非你做得不对。你能编辑帖子并显示查询中使用的所有表格吗?用你正在使用的数据库标记你的问题。下面给出的答案应该已经有效了,除非你做错了。你能编辑帖子并显示查询中使用的所有表格吗?用你正在使用的数据库标记你的问题。