将n与SQL

时间:2018-03-26 11:12:51

标签: mysql sql

编写一个SQL语句,该语句可以生成客户列表,其分钟流量始终小于前一分钟流量。在几分钟内,第n个顺序的流式传输时间小于几分钟,以第n个顺序流式传输,下一个先前的顺序也更少。另一种说法,列出每次观看电影时观看的分钟越来越少的顾客。

表格,查询:

sqlfiddle link:

我提出了以下问题:

select distinct c1.customer_Id
from Customer c1
join Customer c2 
where c1.customer_Id = c2.customer_Id
  and c1.purchaseDate > c2.purchaseDate
  and c1.minutesStreamed < c2.minutesStreamed;

此查询不处理(n-1)st和(n-2)nd比较,即“按n顺序流式传输的分钟数小于分钟数n-1顺序流式传输,以及下一个先前顺序也少了。“条件。

我附上了sqlfiddle的链接,我在这里创建了表格。

3 个答案:

答案 0 :(得分:0)

Hello Continuous Learner,

以下声明适用于n-1n-2关系。

select distinct c1.customer_Id 
from Customer c1 
join Customer c2 
on c1.customer_Id = c2.customer_Id
join Customer c3
on c1.customer_Id = c3.customer_Id
where c1.purchaseDate < c2.purchaseDate
and c1.minutesStreamed > c2.minutesStreamed
and c2.purchaseDate < c3.purchaseDate
and c2.minutesStreamed > c3.minutesStreamed 

虽然,我目前还没有针对此问题的自动解决方案。

干杯

答案 1 :(得分:0)

我会使用带有客户ID分区的ROW_NUMBER()函数。 然后在客户ID和排名=排名-1上进行自我加入,以便在同一级别带来新旧

像: create temp_rank_table as ( select customer_Id, purchaseDate , minutesStreamed, ROW_NUMBER() OVER (PARTITION BY customer_Id, ORDER BY purchaseDate, minutesStreamed) as cust_row from Customer )

自我加入

select customer_Id ( select newval.customer_Id, sum(case when newval.minutesStreamed < oldval.minutesStreamed then 1 else 0 end) as LessThanPrevCount, max(newval.cust_row) as totalStreamCount from temp_rank_table newval left join temp_rank_table oldval on newval.customer_id = oldval.customer_id and newval.cust_row-1 = oldval.cust_row -- cust_row 2 matches to cust_row 1 group by newval.customer_id )A where A.LessThanPrevCount = (A.totalStreamCount-1) -- get customers who always stream lesser than previous --you can use having clause instead of a subquery too

答案 2 :(得分:0)

以@TBL AS TABLE([NO] INT,[CODE] VARCHAR(50),[AREA] VARCHAR(50))

/ *示例1 * /插入@TBL([NO],[CODE],[AREA])值 (1,'001','A00')插入@TBL([NO],[CODE],[AREA])值 (2,'001','A00')插入@TBL([NO],[CODE],[AREA])值 (3,'001','B00')插入@TBL([NO],[CODE],[AREA])值 (4,'001','C00')插入@TBL([NO],[CODE],[AREA])值 (5,'001','C00')插入@TBL([NO],[CODE],[AREA])值 (6,'001','A00')插入@TBL([NO],[CODE],[AREA])值 (7,'001','A00')

/ *示例2 / / *****使用此代码从直接表中输入数据 ***** SELECT ROW_NUMBER()OVER(按[FIELD_DATE]顺序)AS [NO],[FIELD_CODE] AS [CODE],[FIELD_AREA] AS [AREA]从TABLE_A在哪里 CAST([FIELD_DATE] AS DATE)> = CAST('20200307'AS DATE)ORDER BY [FIELD_DATE],[FIELD_CODE] * /

选择A.NO作为ANO,A.CODE作为ACODE,A.AREA作为AAREA,B.NO作为BNO ,B.CODE为BCODE,B.AREA为BAREA,则当A.AREA = B.AREA时 @TBL中的[比较区域]以'Equal'或'N'Equal''结尾 @TBL B ON A.NO = B.NO + 1

Blockquote