Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL-选择SQL中一个字段上没有重复的记录?_Sql_Sql Server - Fatal编程技术网

SQL-选择SQL中一个字段上没有重复的记录?

SQL-选择SQL中一个字段上没有重复的记录?,sql,sql-server,Sql,Sql Server,表1 表2 --------------------- | Template_ID | Product_ID --------------------- | T1 | P1 | | T1 | P5 | | T1 | P5 | | T2 | P10 | | T2 | P45 | 预期的联接查询结果: ------------------------------------------ | Cus

表1


表2

---------------------
| Template_ID | Product_ID  
---------------------
| T1   |  P1   |    
| T1   |  P5   |    
| T1   |  P5   |    

| T2    |  P10   |    
| T2    |  P45   |    
预期的联接查询结果:

------------------------------------------
| Customer_ID | Template_ID  | Product_ID  
------------------------------------------
| C1          |  T1          |  P1
| C1          |  T1          |  P5

| C1          |  T2          |  P10
| C1          |  T2          |  P45

.
.
对于模板,我只想获得上面所示的唯一产品ID。目前,我的查询返回P5两次

.
.
| C1          |  T1          |  P5
| C1          |  T1          |  P5
.
.
我如何在查询级别处理这个问题

使用不同的

  select distinct t1.*,t2.productid
  from table1 t1 join table2 t2 on t1.Template_ID  =t2.Template_ID  

使用
DISTINCT
消除重复项。它不仅适用于第一列,而且适用于整行

例如:

select distinct t1.customer_id, t1.template_id, t2.product_id
from t1
join t2 on t2.template_id = t1.template_id

您只需按要唯一的字段进行分组,因此产品ID:

SELECT Customer_ID,  Template_ID, Product_ID
FROM table1
JOIN table2 using ( Template_ID )
GROUP BY Product_ID;
请试试这个

SELECT 
    DISTINCT A.Customer_ID ,A.Template_ID  ,B.Product_ID   
FROM 
    table1 AS A
INNER JOIN table2 AS B
ON A.Template_ID   = B.Template_ID  

表2的主键是什么?@SyAu create fiddle not text
SELECT 
    DISTINCT A.Customer_ID ,A.Template_ID  ,B.Product_ID   
FROM 
    table1 AS A
INNER JOIN table2 AS B
ON A.Template_ID   = B.Template_ID