我有以下任务:
找到每个购买至少2台笔记本电脑和最多一台电脑的客户。不使用分组就可以。
我需要在下面的交易表中执行此操作,如下所示:
| clientID | typeOfDevice | transactionDate |
它包含每笔交易的记录。 我需要一个不使用GROUP BY的查询。有什么想法吗?
答案 0 :(得分:1)
在MySQL中,您可以使用相关的子查询来执行此操作:
SELECT clientID
FROM (
SELECT DISTINCT clientID,
(SELECT COUNT(*)
FROM mytable AS t2
WHERE t1.clientID = t2.clientID AND
typeOfDevice = 'Laptop') AS laptops,
(SELECT COUNT(*)
FROM mytable AS t2
WHERE t1.clientID = t2.clientID AND
typeOfDevice = 'PC') AS pcs
FROM mytable AS t1 ) AS t
WHERE t.laptops >= 2 AND t.pcs <=1;
答案 1 :(得分:0)
SQL Server
解决方案:
WITH cte AS
(
SELECT DISTINCT clientId
,COUNT(CASE WHEN typeOfDevice = 'laptop' THEN 1 END)
OVER (PARTITION BY clientId) AS laptop
,COUNT(CASE WHEN typeOfDevice = 'PC' THEN 1 END)
OVER (PARTITION BY clientId) AS PC
FROM table_name
)
SELECT *
FROM cte
WHERE laptop >= 2 AND PC <=1;
的 LiveDemo
强>