我有这张" Letter_Senders":
的表格> LETTER_ID | SENDER | RECIPIENT
> 123 | John | David
> 234 | Josh | Andrew
> 345 | David | John
> 456 | Matt | David
> 567 | David | Matt
> 678 | John | David
我非常感谢帮助总结每对人民之间发送的信件数量,如下所示" Counting_Letters"表:
Person_1 | Person_2 | Num_Of_Letters
John | David | 3
Josh | Andrew | 1
Matt | David | 2
试图弄清楚但不知道,需要考虑从两个人方只计算一次。
答案 0 :(得分:2)
如果您的dbms支持greatest
和least
等功能,请使用
SELECT greatest(person_1,person_2) AS person_1,
least(person_1,person_2) AS person_2,
count(*) AS num_letters
FROM letter_senders
GROUP BY greatest(person_1,person_2),
least(person_1,person_2)
也可以使用case
表达式来实现。
SELECT CASE
WHEN person_1>person_2 THEN person_1
ELSE person_2
END AS person_1,
CASE
WHEN person_1<person_2 THEN person_1
ELSE person_2
END AS person_2,
count(*) AS num_letters
FROM letter_senders
GROUP BY CASE
WHEN person_1>person_2 THEN person_1
ELSE person_2
END,
CASE
WHEN person_1<person_2 THEN person_1
ELSE person_2
END
答案 1 :(得分:1)
我想出了与vkp相同的答案(在相同的假设下工作):
IF OBJECT_ID('tempdb..#Test') IS NOT NULL
DROP TABLE #Test
CREATE TABLE #Test
(
LETTER_ID INT
,SENDER VARCHAR(20)
,RECIPIENT VARCHAR(20)
)
INSERT #Test
VALUES
(123, 'John', 'David'),
(234, 'Josh', 'Andrew'),
(345, 'David', 'John'),
(456, 'Matt', 'David'),
(567, 'David', 'Matt'),
(678, 'John', 'David')
SELECT
CASE
WHEN SENDER < RECIPIENT
THEN SENDER
ELSE RECIPIENT
END [Person_1]
,CASE
WHEN SENDER > RECIPIENT
THEN SENDER
ELSE RECIPIENT
END [Person_2]
,COUNT(*) [Num_Of_Leters]
FROM #Test
GROUP BY CASE
WHEN SENDER < RECIPIENT
THEN SENDER
ELSE RECIPIENT
END
,CASE
WHEN SENDER > RECIPIENT
THEN SENDER
ELSE RECIPIENT
END
答案 2 :(得分:0)
WITH
letters (sender, recipient, num_of_letters) AS
(
SELECT
sender
, recipient
, COUNT(*) num_of_letters
FROM
letter_senders
GROUP BY
sender
, recipient
)
SELECT
person_1 sent.sender
, person_2 sent.recipient
, num_of_letters sent.num_of_letters + received.num_of_letters
FROM letters_sent sent
INNER JOIN letters_sent received
ON
(sent.sender = received.sender AND sent.recipient = received.recipient)
OR (sent.recipient = received.sender AND sent.sender = received.recipient)