繁体   English   中英

如何计算SQL中的出现次数

[英]How to count occurrence in SQL

我有一个清单(例如衬衫、上衣、裤子、阿迪达斯、耐克、彪马等)和年份,格式如下 2017-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
select year, purchases, count(*)
from table
group by year, purchase
order by 1, 2

您可以使用group byorder by

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;

SELECT使用=表明您正在使用 SQL Server。 SQL Server 不支持在GROUP BY使用别名,因此您需要重复该表达式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM