【发布时间】:2015-12-18 03:18:34
【问题描述】:
我有以下 3 个表:
POS_Transactions(TransactionDate,TerminalID,TransactionTypeID,TotalAmount)
Terminal(TerminalID,CountryID)
Country(CountryID,CountryName,CurrencyName)
现在我正在使用内部连接来链接这些表,但我没有得到想要的结果,即它没有分组 Country-wise
SELECT C.countryname 'CountryName',
C.currencyname 'CurrencyName',
transactiondate,
Sum(CASE transactiontypeid
WHEN 6 THEN 1
ELSE 0
END) 'Number of Cards Issue',
Sum(CASE transactiontypeid
WHEN 6 THEN totalamount
ELSE 0
END) 'Total Amount Loaded',
Count(DISTINCT CASE transactiontypeid
WHEN 4 THEN pan
ELSE NULL
END)'Number of Card Redeemed',
Sum(CASE transactiontypeid
WHEN 4 THEN 1
ELSE 0
END) 'Number of Sales Transaction',
Sum(CASE transactiontypeid
WHEN 4 THEN totalamount
ELSE 0
END) 'Total Values of Sale Transaction'
INTO #temp
FROM pos_transactions p
INNER JOIN terminal T
ON T.terminalid = p.terminalid
INNER JOIN country C
ON T.countryid = C.countryid
GROUP BY transactiondate,
C.countryname,
C.currencyname,
C.countryid
select [Number of Cards Issue],[Total Amount Loaded], [Number of Card Redeemed],[Number of Sales Transaction],
[Total Values of Sale Transaction],CountryName,CurrencyName from #temp
where (TransactionDate >= @DateFrom)
and (TransactionDate < @DateTo)
drop table #temp
例如,如果 Transactions 在阿联酋 Country 中有两条记录,那么它显示的是单独的结果:
(CountryName,Numbers of Cards Issued,CurrencyName,Total Amount Loaded,Number of Sales Transaction,Total Values of Sale Transaction)
UAE 1 SAR 320.000 0 0.0000
UAE 2 SAR 320.000 0 0.0000
相反,它应该对CountryUAE 的结果进行分组。应该是
UAE 3 SAR 640.000 0 0.0000
我做错了什么?
【问题讨论】:
-
结果中的 1 和 2 是什么?
-
从
group by中删除TransactionDate。您可能还需要修复查询的其他部分。 -
在您的结果中,一列在哪里结束,另一列从哪里开始?在结果集中添加列名。
-
您的查询与示例数据不匹配。我不喜欢猜谜游戏..
-
抱歉,我错过了与交易日期相关的部分。它用于过滤记录。我已经编辑了我的帖子
标签: sql sql-server group-by inner-join