我需要显示来自下表的汇总结果,但仅当两列(TransactionType, ClientId
)的一对独特时才会显示。
我当前的查询
SELECT
SUM(OrderQty), ClientId, OrderId
FROM
Table
GROUP BY
ClientId, TransactionType
HAVING
COUNT(DISTINCT(TransactionType, ClientId)) > 1
输出:
TransactionType ClientId Product OrderQty
--------------------------------------------
123 A01 Apples 10
123 A22 Apples 20
222 A01 Book 20
222 A01 Car 20
555 A09 Book 20
555 A09 Oranges 20
999 A01 Apples 10
999 A22 Apples 20
期望输出
TransactionType ClientId Product OrderQty
--------------------------------------------
123 A01 Apples 10
123 A22 Apples 20
999 A01 Apples 10
999 A22 Apples 20
答案 0 :(得分:3)
您可以使用与当前查询类似的派生表,并将其连接到原始表以获取结果:
SELECT s.* FROM YourTable s
INNER JOIN (SELECT t.transactionType , t.product
FROM YourTable t
GROUP BY t.transactionType , t.product having COUNT(*) > 1) ss
ON(s.transactionType = t.transactionType and s.product = t.product)
这将为您提供预期的输出。
答案 1 :(得分:2)
查看所需的输出(这与标题完全矛盾)。
SELECT ClientId,TransactionType, Min(OrderId) as OrderId, Min(OrderQty) as OrderQty
FROM Table
GROUP BY ClientId,TransactionType
HAVING COUNT(*) = 1
答案 2 :(得分:1)
SELECT
t.TransactionType,
t.ClientId,
t.Product,
t.OrderQty
FROM
Table t
JOIN
(SELECT
ClientId,
TransactionType
FROM
Table
GROUP BY
ClientId,
TransactionType
HAVING
COUNT(*) > 1) AS a
ON t.ClientId = a.ClientId
AND t.TransactionType = a.TransactionType
答案 3 :(得分:1)
-- Temp table with the example data
IF OBJECT_ID('tempdb..#Tbl') IS NOT NULL
DROP TABLE #Tbl
SELECT A.*
INTO #Tbl
FROM
(
SELECT 123 TransactionType, 'A01' ClientId, 'Apples' Product, 10 OrderQty
UNION SELECT 123,'A22','Apples',20
UNION SELECT 222,'A01','Book',20
UNION SELECT 222,'A01','Car',20
UNION SELECT 555,'A09','Book',20
UNION SELECT 555,'A09','Oranges',20
UNION SELECT 999,'A01','Apples',10
UNION SELECT 999,'A22','Apples',20
) A
-- Requested query
SELECT
B.TransactionType
,B.ClientId
,B.Product
,B.OrderQty
FROM
(
SELECT
T.TransactionType
,T.ClientId
,T.Product
,T.OrderQty
,COUNT(1) OVER(PARTITION BY T.TransactionType,T.ClientId) N
FROM #Tbl T
)
B
WHERE B.N = 1