如何将记录与Transact-SQL分组?
我需要在数据库中对相同的记录进行分组。我的代码:
SELECT
FirstName, LastName, FullDateAlternateKey
FROM
((AdventureWorksDW2012..FactInternetSales
INNER JOIN
AdventureWorksDW2012..DimProduct ON FactInternetSales.ProductKey = DimProduct.ProductKey)
INNER JOIN
AdventureWorksDW2012..DimDate ON DimDate.DateKey = FactInternetSales.DueDateKey)
INNER JOIN
AdventureWorksDW2012..DimCustomer ON DimCustomer.CustomerKey = FactInternetSales.CustomerKey
WHERE
YEAR(FullDateAlternateKey) LIKE '2013'
AND MONTH(FullDateAlternateKey) LIKE '12'
我得到的:
名字 | 姓氏 | 日期 |
---|---|---|
Eugene | Huang | 2013-12-22 |
Eugene | Huang | 2013-12-22 |
Eugene | Huang | 2013-12-22 |
Eugene | Huang | 2013-12-22 |
喜欢 | Lal | 2013-12-22 |
喜欢 | Lal | 2013-12 -22 |
喜欢 | 拉尔 | 2013-12-11 |
喜欢 | 拉尔 | 2013-12-11 |
喜欢 | Lal | 2013-12-12 |
喜欢 | Lal | 2013-12-12 |
Jaclyn | Lu | 2013-12-01 |
我需要记录是这样的:
FIRSTNAME | LASTNAME | 日期 |
---|---|---|
Eugene | Huang | 2013-12-22 |
喜欢 | Lal | 2013-12 -22 |
等。
如果我添加,
GROUP BY FirstName, LastName
我会收到此错误:
选择列表中不允许使用“AdventureWorksDW2012...DimDate.FullDateAlternateKey”列,因为它不包含在聚合函数或 GROUP BY 语句中。
I need to group the same records at the database. My code:
SELECT
FirstName, LastName, FullDateAlternateKey
FROM
((AdventureWorksDW2012..FactInternetSales
INNER JOIN
AdventureWorksDW2012..DimProduct ON FactInternetSales.ProductKey = DimProduct.ProductKey)
INNER JOIN
AdventureWorksDW2012..DimDate ON DimDate.DateKey = FactInternetSales.DueDateKey)
INNER JOIN
AdventureWorksDW2012..DimCustomer ON DimCustomer.CustomerKey = FactInternetSales.CustomerKey
WHERE
YEAR(FullDateAlternateKey) LIKE '2013'
AND MONTH(FullDateAlternateKey) LIKE '12'
What I get:
FIRSTNAME | LASTNAME | DATE |
---|---|---|
Eugene | Huang | 2013-12-22 |
Eugene | Huang | 2013-12-22 |
Eugene | Huang | 2013-12-22 |
Eugene | Huang | 2013-12-22 |
Like | Lal | 2013-12-22 |
Like | Lal | 2013-12-22 |
Like | Lal | 2013-12-11 |
Like | Lal | 2013-12-11 |
Like | Lal | 2013-12-12 |
Like | Lal | 2013-12-12 |
Jaclyn | Lu | 2013-12-01 |
I need to records would be like this:
FIRSTNAME | LASTNAME | DATE |
---|---|---|
Eugene | Huang | 2013-12-22 |
Like | Lal | 2013-12-22 |
and so on.
If I add
GROUP BY FirstName, LastName
I get this error:
The "AdventureWorksDW2012...DimDate.FullDateAlternateKey" column is not allowed in the selection list because it is not contained in either the aggregate function or the GROUP BY sentence.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要每个名称和最后一个名称的最大日期,因此您
组由FirstName,LastName
和SELECTmax(FulldateAteAlternateKey)
。 (顺便说一句,fulldatealternatekey是日期的奇怪名称。)加入到
dimproduct
似乎是多余的。可以改善日期条件。You want the maximum date per FirstName and LastName, so you
GROUP BY FirstName, LastName
and selectMAX(FullDateAlternateKey)
. (FullDateAlternateKey is a strange name for a date by the way.)The join to
DimProduct
seems superfluous. The date condition can be improved.