SQL:根据没有GROUP BY的事件进行选择

时间:2015-11-10 11:05:08

标签: mysql sql sql-server

我有以下任务:

找到每个购买至少2台笔记本电脑和最多一台电脑的客户。不使用分组就可以。

我需要在下面的交易表中执行此操作,如下所示:

| clientID | typeOfDevice | transactionDate |

它包含每笔交易的记录。 我需要一个使用GROUP BY的查询。有什么想法吗?

2 个答案:

答案 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;

Demo here

答案 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