简体   繁体   English

按计数多个表分组

[英]Group by count multiple tables

Need to find out why my group by count query is not working.需要找出为什么我的按计数分组查询不起作用。 I am using Microsoft SQL Server and there are 2 tables I am trying to join.我正在使用 Microsoft SQL 服务器,我正在尝试加入 2 个表。

My query needs to bring up the number of transactions made for each type of vehicle.我的查询需要显示为每种类型的车辆进行的交易数量。 The output of the query needs to have a separate row for each type of vehicle such as ute, hatch, sedan, etc.查询的 output 需要为每种类型的车辆(例如 ute、hatch、轿车等)有一个单独的行。

CREATE TABLE vehicle
(
     vid   INT PRIMARY KEY,
     type  VARCHAR(30) NOT NULL,
     year  SMALLINT NOT NULL,
     price DECIMAL(10, 2) NOT NULL,
);

INSERT INTO vehicle
VALUES (1, 'Sedan', 2020, 240)

CREATE TABLE purchase
(
     pid        INT PRIMARY KEY,
     vid        INT REFERENCES vehicle(vid),
     pdate      DATE NOT NULL,
     datepickup DATE NOT NULL,
     datereturn DATE NOT NULL,
);

INSERT INTO purchase
VALUES (1, 1, '2020-07-12', '2020-08-21', '2020-08-23') 

I have about 10 rows on information in each table I just haven't written it out.我在每个表中都有大约 10 行信息,我只是没有写出来。

This is what I wrote but it doesn't return the correct number of transactions for each type of car.这是我写的,但它没有为每种类型的汽车返回正确的交易数量。

SELECT 
    vehicle.vid,
    COUNT(purchase.pid) AS NumberOfTransactions
FROM   
    purchase
JOIN 
    vehicle ON vehicle.vid = purchase.pid
GROUP BY 
    vehicle.type; 

Any help would be appreciated.任何帮助,将不胜感激。 Thanks.谢谢。

Your GROUP BY and SELECT columns are inconsistent.您的GROUP BYSELECT列不一致。 You should write the query like this:您应该像这样编写查询:

SELECT v.Type, COUNT(*) AS NumPurchases
FROM Purchase p JOIN
     Vehicle v
     ON v.vID = p.pID
GROUP BY v.Type;

Note the use of table aliases so the query is easier to write and read.请注意表别名的使用,以便查询更易于编写和阅读。

If this doesn't produce the expected values, you will need to provide sample data and desired results to make it clear what the data really looks like and what you expect.如果这没有产生预期值,您将需要提供样本数据和所需结果,以明确数据的真实外观和您的期望。

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

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