SQL(子查询)

时间:2016-09-02 11:09:42

标签: sql sql-server-2008

我想继续使用SQL查询进行额外的步骤,我想要运行。

我有一个客户数据库,其中包含客户表,其中包含客户加入时的日期/时间详细信息以及包含其年度交易详情的交易表

我想要做的是按加入日期(作为年份)进行分组并计算每年加入的数字,然后在下一栏中我想计算拥有的数字在特定年份交易例如2016年是当年。通过这种方式,我可以显示多年来的客户保留率。

这两个表都是由客户URN链接的,但我正在努力探索最有效的方式展示这一点。我可以通过加入年份轻松统计和分组成员,我可以显示最大日期交易,但我正在努力将两者结合在一起。我想我需要使用子查询和左连接,但它暗指我。

带有数据

的输出列标题示例

Year_Joined = 2009

Joiner_Count = 10

Transact_in_2016 = 5

我在语法方面。我知道这不是接近完成的地方。因为我需要按DateJoined进行分组,然后查询2016年已交易的客户数量?

SELECT Customer.URNCustomer,
       MAX(YEAR(Customer.DateJoined)),
       MAX(YEAR(Tran.TranDate)) As Latest_Tran,
FROM Mydatabase.dbo.Customer   
LEFT JOIN Mydatabase.dbo.Tran
    ON Tran.URNCustomer = Customer.URNCustomer
GROUP BY Customer.URNCustomer
ORDER BY Customer.URNCustomer

2 个答案:

答案 0 :(得分:2)

最好的方法是在进行连接之前进行聚合。你想要计算两个不同的东西,所以要单独计算它们并将它们组合起来。

以下使用full outer join。这样可以处理多年没有新客户的情况和没有交易的年份:

select coalesce(c.yyyy, t.yyyy) as yyyy,
       coalesce(c.numcustomers, 0) as numcustomers,
       coalesce(t.numtransactions, 0) as numtransactions
from (select year(c.datejoined) as yyyy, count(*) as numcustomers
      from Mydatabase.dbo.Customer c
      group by year(c.datejoined)
     ) c full outer join
     (select year(t.trandate) as yyyy, count(*) as numtransactions
      from database.dbo.Tran t
      group by year(t.trandate)
     ) t
     on c.yyyy = t.yyyy;

答案 1 :(得分:0)

你可能想尝试这样的事情:

def index
  @user = current_user
  @favorites = @user.favorites
  @tools = @user.tools.order("created_at DESC")
end



%h2 My Favorite Tools
- @favorites.each do |tool|
    = image_tag tool.cover_filename.url
    %h2= link_to tool.title, tool
    %p= tool.subtitle
    %p= tool.impressionist_count
    %p= link_to tool.get_upvotes.size, like_tool_path(tool), method: :get
    %p= link_to "Edit", edit_tool_path(tool)
    %p
        http://ocubit.com/tools/
        = tool.id
    %p= time_ago_in_words(tool.created_at)

%h2 My Tools
- @tools.each do |tool|
    = image_tag tool.cover_filename.url
    %h2= link_to tool.title, tool
    %p= tool.subtitle
    %p= tool.impressionist_count
    %p= link_to "Edit", edit_tool_path(tool)
    %p
        http://ocubit.com/tools/
        = tool.id
    %p= time_ago_in_words(tool.created_at)


= link_to "View Your Profile", '/users/'+@user.id.to_s

-if @user.use_gravatar?
    = image_tag gravatar_for @user
- else
    = image_tag @user.avatar_filename.url

%h1= @user.username

= link_to "Edit", edit_user_registration_path