我有一张桌子,我想要输出如下 只想要不同的价值观。 我使用交叉申请但不起作用。
Customer Book
C1 B1
C2 B1
C3 B1
我需要输出:所有客户的所有组合。只有不同的值
示例:
Customers
C1,C2
C1,C3
C2,C3
答案 0 :(得分:2)
您可以使用主键列
执行此操作CREATE TABLE #TAB( ID INT IDENTITY,Customer VARCHAR(10), Book VARCHAR(10))
INSERT INTO #TAB
SELECT 'C1','B1'
UNION ALL
SELECT 'C2','B1'
UNION ALL
SELECT 'C3','B1'
SELECT T2.Customer ,T.Customer
FROM #TAB T
INNER JOIN #TAB T2 ON T.ID >T2.ID
结果:
+----------+----------+
| Customer | Customer |
+----------+----------+
| C1 | C2 |
| C1 | C3 |
| C2 | C3 |
+----------+----------+
答案 1 :(得分:1)
如果您希望客户使用相同的图书,则查询应该类似。注意<运算符,因为我们想要(C1,C2),而不是(C2,C1):
select distinct a.customer_col , b.customer_col
from customer_table a join customer_table b
on a.book_col = b.book_col and a.customer_col < b.customer_col
答案 2 :(得分:1)
这应该有用,至少对你的样本数据和叙述而言:
select distinct case when t1.customer > t2.customer then t2.customer + ',' + t1.customer else t1.customer + ',' + t2.customer end
from tbl t1
join tbl t2
on t1.book = t2.book
and t1.customer <> t2.customer
答案 3 :(得分:0)
希望我能正确理解问题,
请检查以下查询。请用原始表格替换表格和列。
Rextester链接 - http://rextester.com/RPPXQO21553
select
a.customer_col , b.customer_col , a.rn , b.rn
from
(select customer_col , row_number() over (order by customer_col) rn from customer_table) a join
(select customer_col , row_number() over (order by customer_col) rn from customer_table) b
on a.customer_col <> b.customer_col
and a.rn < b.rn
order by 1
;
答案 4 :(得分:0)
您可以使用自我加入来实现这一目标(希望您希望客户拥有相同的书籍),下面的示例脚本
select t1.customer,t2.customer
from @tble t1
inner join @tble t2 on t1.book = t2.book
and t1.customer < t2.customer
答案 5 :(得分:0)
我得到了答案
select B,A from(select a.customer A,b.customer B, ROW_NUMBER() over(order by a.customer)rn from CustomerData a
JOIN CustomerData b ON a.customer>b.customer )x