SQL Server 查询 LEFT JOIN、SUM 和 GROUP BY,我被难住了!

SQL Server Query LEFT JOIN, SUM and GROUP BY and I#39;m stumped!(SQL Server 查询 LEFT JOIN、SUM 和 GROUP BY,我被难住了!)
本文介绍了SQL Server 查询 LEFT JOIN、SUM 和 GROUP BY,我被难住了!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用我的大脑来对抗这个

I am beating my brain against this one

我有 3 个 SQL Server 2005 表

I have 3 SQL Server 2005 tables

用户奖励:

id, awardamount, userid, dateawarded, awardtypeid 

用户:

id, firstname, lastname

奖励类型:

id, title

所以如果 awards 表有行

1, 300.00, 3, 01-01-2011, 1
2, 125.00, 3, 01-05-2011, 1
3,  50.00, 2, 01-05-2011, 2

用户表行

1, john, smith
2, mark, smith
3, bob, smith

奖励类型

1, cash
2, prize

我希望输出看起来与此类似

and I want the output to look similar to this

bob smith, 425.00, cash
mark smith, 50, prize

等等等等

一个用户可以有多个奖励,结果需要显示唯一用户,但有总奖励金额.此外,还需要 2 个连接,一个用于获取用户表中的用户名/姓和奖励类型标题.

A user can have multiple awards, the results need to display unique users, but with there total award amount. in addition there needs to be 2 joins, one, to grab the users first name/last that's in a user table and the award type title.

所以我的查询看起来像这样(我知道它不起作用)

So my query is looking like this (i know it doesn't work)

SELECT id, userid, awardtypeid, SUM(awardamount) 
FROM awards a
LEFT JOIN userinfo ui ON ui.userid = a,userid
LEFT JOIN awardtypes ON awardtypesid = a.awardtypeid
GROUP BY userid

这可能吗?

推荐答案

你可能想要

SELECT userid, 
       awardtypeid, 
       SUM(awardamount) 
FROM   awards a 
       LEFT JOIN userinfo ui 
         ON ui.userid = a.userid 
       LEFT JOIN awardtypes 
         ON awardtypesid = a.awardtypeid 
GROUP  BY userid, 
          awardtypeid 

SELECT userid, 
       SUM(awardamount) 
FROM   awards a 
       LEFT JOIN userinfo ui 
         ON ui.userid = a.userid 
       LEFT JOIN awardtypes 
         ON awardtypesid = a.awardtypeid 
GROUP  BY userid

这会删除 id 列(可能不是您想要分组的内容)

This drops the id Column (probably not what you want to group on)

在第一种情况下,我在 select 中包含了 Awardtypeid,但这意味着您还必须将其添加到 group by.

In the first case I included the awardtypeid in the select but this means you must also add that to the group by.

这篇关于SQL Server 查询 LEFT JOIN、SUM 和 GROUP BY,我被难住了!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)