SQL根据列中的值显示结果

时间:2018-05-23 00:56:12

标签: sql sql-server web-sql

所以我在Web SQL中有2个表,其中一个看起来像这样(有数千行):

    customer_number        |       order_number
--------------------------------------------
1234                              12
1234                              13
1234                              14
6793                              20
6793                              22
3210                              53

etc.

另一张表就像这样(也有数千行):

customer_number        |       first_purchase_year
----------------------------------------------------
1234                              2010
5313                              2001
1632                              2018
9853                              2017
6793                              2000
3210                              2005

etc.

我有这个代码从第一个表中选择10个客户并列出他们的所有购买:

select top 10 * from
(select distinct t1.customer_number, 
    stuff((select '' + t2.order_number
                from orders t2
                where t1.customer_number = t2.customer_number
                for xml path(''), type
                ).value('.','NVARCHAR(MAX)')
            ,1,0,'')DATA
from orders t1) a

Whch输出:

    customer_number        |       order_number
--------------------------------------------
1234                              12 13 14
6793                              20 22
3210                              53

我需要做的只是显示10个拥有first_purchase_year>的随机客户2010。 我不确定如何检查对应于customer_number的first_purchase_year是否大于2010。 谢谢!

1 个答案:

答案 0 :(得分:0)

您只需要在外部from子句中修复子查询:

select c.customer_number, 
       stuff((select '' + o2.order_number
              from orders o2
              where c.customer_number = o2.customer_number
              for xml path(''), type
             ).value('.','NVARCHAR(MAX)'
                    ), 1, 0, ''
            ) as data
from (select top (10) c.customer_number
      from table2 c
      where c.first_purchase_year > 2010
     ) c;