按所有列分组的速记方式?

huangapple go评论63阅读模式
英文:

Shorthand for group by all columns?

问题

我有一个包含15列客户信息的表,我想将他们的购买总额与表格连接起来。我目前正在尝试以下连接:

SELECT  A.*, SUM(B.SALES_AMT) AS SALES
FROM CUST_INFO A
LEFT JOIN SALES_TABLE B
ON A.Cust_ID = B.Cust_ID
GROUP BY fooa, foob, fooc, etc

是否有一种方法可以使用GROUP BY A.*而不必写出所有15列左右的列名?

英文:

I have a table with 15 columns with customer info and I want to join the sum of their purchases onto the table. I am currently attempting the following join:

SELECT  A.*, SUM(B.SALES_AMT) AS SALES
FROM CUST_INFO A
LEFT JOIN SALES_TABLE B
ON A.Cust_ID = B.Cust_ID
GROUP BY fooa, foob, fooc, etc

Is there a way to group by where I can simply say GROUP BY A.* instead of having to write out all 15 or so columns?

答案1

得分: 3

你可以将求和部分移到 apply 中:

select  A.*, Isnull(B.SALES, 0) SALES
from CUST_INFO A
outer apply (
  select Sum(B.SALES_AMT) SALES
  from SALES_TABLE B
  where B.Cust_ID = A.Cust_ID
)B;
英文:

You could move the sum into an apply:

select  A.*, Isnull(B.SALES, 0) SALES
from CUST_INFO A
outer apply (
  select Sum(B.SALES_AMT) SALES
  from SALES_TABLE B
  where B.Cust_ID = A.Cust_ID
)B;

答案2

得分: 2

将您的销售数据分组在一个子查询中

SELECT A.*, B.SALES
FROM CUST_INFO A
LEFT JOIN (
  SELECT B.Cust_ID, SUM(B.SALES_AMT) SALES
  FROM SALES_TABLE B
  GROUP BY B.Cust_ID
) B ON A.Cust_ID = B.Cust_ID;
英文:

Group your sales data in a sub-query

SELECT A.*, B.SALES
FROM CUST_INFO A
LEFT JOIN (
  SELECT B.Cust_ID, SUM(B.SALES_AMT) SALES
  FROM SALES_TABLE B
  GROUP BY B.Cust_ID
) B ON A.Cust_ID = B.Cust_ID;

huangapple
  • 本文由 发表于 2023年6月9日 04:33:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76435504.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定