简体   繁体   中英

Select distinct duplicated rows from 1:n tables in SQL Server

I am trying to select customers and their orders in one query, but I get customer and his orders in datatable which customer table columns repeated for each order.
I tried DISTINCT , GROUP BY but can't do it.

SQL:

select * 
from Customer, Order 
where Order.CustomerID = Customer.CustomerID 
  and Customer.CustomerID = '2'

Tables:

表格检视

Since there cannot be different columns for each row you can't do it without having duplicates. Consider reading data separately, once for the customer and once for her orders.

i want to get all customers and orders the query count will grow.if i have 3 customer i want to get orders and customers in one query.not 6 times query execution.

You do not need to perfrom a separate query for each customer. You just need a single query for all customers and a single query for all orders. Then you may connect them in application layer rather than a single query.

But if you argue that you have too many customers and too many orders to hold them all in memory, well, then you may perform a separate query for each customer. That's a tradeoff between memory and CPU.

This is a very rare query, but this my understanding of your need :p.

select *
from (
    select 'CustomerID' as col1, 'CustomerName' as col2, 'ContactName' as col3,
        'Address' as col4, 'City' as col5, 'PostalCode' as col6, 'Country' as col7, 0 as ord
    union all
    select CustomerID, CustomerName, ContactName, Address, City, PostalCode, Country, 1 as ord
    from Customers
    union all
    select 'OrderId', 'CustomerID', 'EmployeeID', 'OrderDate', 'ShipperID', Null, Null, 0 as ord
    union all
    select OrderId, CustomerID, EmployeeID, OrderDate, ShipperID, Null, Null, 2 as ord
    from Orders) res

In the result with ord = 0 you have titles, with ord = 1 you will have customers only and with ord = 2 you will have orders, and you can use this query with this condition:

where (col1 = @customerId and ord = 1) or (col2 = @customerId and ord = 2)

You can add or ord =0 if you want to add titles in your output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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