sql - 更新 SQL Server 中 GROUP BY sum() 函数的查询问题
问题描述
SELECT p.userId, u.username, SUM(p.prices)Price
FROM tblPrices p, tblUsers u
WHERE u.userId = p.userId
GROUP BY p.userId, u.username
我想更新Price
结果
解决方案
https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=cb7049e35720e92e5bee4a678b5283d3
在 SQL Server 中,您有两种创建表的途径。显式CREATE TABLE
语句,您在其中显式定义表结构。另一个是通过 SELECT 语句的可选INTO
子句管理的。SQL 引擎将识别结果集的形状,然后创建一个与您的结果完全匹配的表。这也将立即将查询的任何结果加载到表中,但这只能工作一次。如果您需要向表中添加更多数据,则必须将查询重写为传统INSERT
语句,并且可能UPDATE
取决于源数据的可变性。另一种方法是删除表并每次重新创建它。正确的选择取决于业务需求和数据适用性。
模拟您的环境
CREATE TABLE dbo.tblPrices
(
userId int NOT NULL
, prices decimal(18,2) NOT NULL
);
create table dbo.tblUsers
(
userId int NOT NULL
,username varchar(50) nOT NULL
);
insert into
dbo.tblUsers
VALUES (1,'mo')
,(2, 'bill')
,(3, 'no sales');
insert into dbo.tblPrices
VALUES
(1, 13)
,(1, 7)
, (2, 17);
查询数据
-- create the table if it doesn't exist
-- blows up otherwise
SELECT
P.userId
, U.username
, SUM(P.prices) AS Prices
INTO
dbo.RESULTS
FROM
dbo.tblPrices AS P
INNER JOIN
dbo.tblUsers AS U
ON U.userId = P.userId
GROUP BY
P.userId
, U.username
;
-- What if we want to see all users, whether they had sales or not
-- Notice the change to a left join as well as reordering of the
-- tables and the use of the users userId as the prices might not exist
SELECT
U.userId
, U.username
, SUM(P.prices) AS Prices
INTO
dbo.RESULTS_ALL_USERS
FROM
dbo.tblUsers AS U
LEFT OUTER JOIN
dbo.tblPrices aS P
ON U.userId = P.userId
GROUP BY
U.userId
, U.username
;
检查结果
SELECT * FROM dbo.RESULTS AS R ORDER BY userID;
SELECT * FROM dbo.RESULTS_ALL_USERS AS R ORDER BY userID;
推荐阅读
- gradle - gradle 一直崩溃,已经尝试删除 gradle 文件夹,甚至尝试重新安装我所有的 IDE,包括 java、flutter 等
- django - 使用带有通配符 CNAME 的 Django 租户在 Heroku 中接收 404 错误
- c# - QueueTriggerAttribute 缺失
- python - 为什么 Python 不调用模块中的函数?
- mariadb - 启动 HeidiSQL 时访问被拒绝消息
- macos - Windows 10 Bootcamp 导致 Oracle Database 11g XE 出现问题
- python - 创建一个占位符,其形状是另一个形状的函数
- quickbooks - 通过 Web 连接器连接到 Quickbooks Desktop POS 时出错
- python - 将 PNG 转换为 Python
- sql-server - SQL Server:在存储过程中查找和删除索引提示