首页 > 解决方案 > SQL多表连接查询字符串中有DISTINCT关键字时如何查询记录数

问题描述

我使用 SQL Server,我的 SQL 命令是:

select distinct 
    table_motor.motor_ID, table_welding_machine.welding_machine_ID 
from 
    table_motor, 
    table_welding_machine, 
    table_joint_point_para, 
    table_motor_production_line 
where 
    table_joint_point_para.welding_machine_ID = table_welding_machine.welding_machine_ID 
    and table_joint_point_para.motor_ID = table_motor.motor_ID 
    and table_motor_production_line.motor_ID = table_motor.motor_ID 
    and 1=1

结果中有 83 条记录。

DISTINCT我的问题是: SQL多表联合查询字符串中有关键字时如何查询记录数?

如果我在字符串中使用 count ,我会收到错误:

列 table_motor.motor_ID 在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。

错误图像

如果我像这样更改我的 SQL 命令,我不会得到记录的总数:

select distinct 
    table_motor.motor_ID, 
    table_welding_machine.welding_machine_ID, 
    count(*) 
from 
    table_motor, 
    table_welding_machine, 
    table_joint_point_para, 
    table_motor_production_line 
where 
    table_joint_point_para.welding_machine_ID = table_welding_machine.welding_machine_ID 
    and table_joint_point_para.motor_ID = table_motor.motor_ID 
    and table_motor_production_line.motor_ID = table_motor.motor_ID 
    and 1=1
group by 
    table_motor.motor_ID, table_welding_machine.welding_machine_ID

结果图像

如何解决这个问题呢?

这个字符串没问题:

select count(distinct (t_test01.tid)) from t_test01, t_test02 where t_test01.tid = t_test02.tid

这个字符串是错误的:',' 附近的语法不正确。

select count(distinct (t_test01.tid, t_test02.value)) from t_test01, t_test02 where t_test01.tid = t_test02.tid

标签: sqlsql-server

解决方案


试试这个查询:

    select * , count(*) as CountOfRecords from (
select distinct 
    table_motor.motor_ID, 
    table_welding_machine.welding_machine_ID
    
from 
    table_motor, 
    table_welding_machine, 
    table_joint_point_para, 
    table_motor_production_line 
where 
    table_joint_point_para.welding_machine_ID = table_welding_machine.welding_machine_ID 
    and table_joint_point_para.motor_ID = table_motor.motor_ID 
    and table_motor_production_line.motor_ID = table_motor.motor_ID 
    and 1=1
group by 
    table_motor.motor_ID, table_welding_machine.welding_machine_ID
) as d group by d.motor_ID, d.welding_machine_ID

推荐阅读