我需要从业务员的2列订单表中获取现金和支票金额之和。
我的桌子是这样的:
def categorical_accuracy(y_true, y_pred):
return K.cast(K.equal(K.argmax(y_true, axis=-1),
K.argmax(y_pred, axis=-1)), K.floatx())
SQL:
Salesman A Cash 21151
Salesman B Cash 34510
Salesman C Cash 21252
Salesman D Cash 13356
Salesman A Cheque 13944
Salesman B Cheque 87368
Salesman C Cheque 20182
Salesman D Cheque 23862
我需要得到这样的结果:
SELECT Ca.Cash, Cr.Credit FROM
(SELECT Salesman, PayMode, SUM(Collection) AS Cash
FROM Prospect_Detail WHERE(Purpose = 'Collections') AND (PayMode = 'Cash')
GROUP BY Salesman, PayMode) AS Ca
CROSS JOIN
(SELECT Salesman, PayMode, SUM(Collection) AS Credit
FROM Prospect_Detail WHERE(Purpose = 'Collections') AND (PayMode = 'cheque')
GROUP BY Salesman, PayMode) Cr
答案 0 :(得分:5)
您可以尝试以下操作。
create table #Temp (name varchar(50), collectionType varchar(10), amount int)
insert into #Temp values
('Salesman A', 'Cash', 21151),
('Salesman B', 'Cash', 34510),
('Salesman C', 'Cash', 21252),
('Salesman D', 'Cash', 13356),
('Salesman A', 'Cheque', 13944),
('Salesman B', 'Cheque', 87368),
('Salesman C', 'Cheque', 20182),
('Salesman D', 'Cheque', 23862)
SELECT name, Cash, cheque
FROM
(SELECT collectionType, name , amount
FROM #Temp) AS SourceTable
PIVOT
(
SUM(amount)
FOR collectionType IN ( Cash , Cheque)
) AS PivotTable;
输出如下所示
name Cash cheque
--------------------------
Salesman A 21151 13944
Salesman B 34510 87368
Salesman C 21252 20182
Salesman D 13356 23862
您可以找到实时演示Here。
答案 1 :(得分:2)
要解决的建议很复杂。别理他们。只需使用条件求和。简化示例:
select Salesman, sum(case Paymode when 'Cash' then Collection else 0 end) as Cash, ...
from Prospect_Detail
where Purpose = 'Collections'
group by Salesman
order by Salesman;
答案 2 :(得分:2)
可以使用PIVOT
运算符来获得所需的结果:
DECLARE @tbl TABLE
(
SalesMan varchar(50),
PayType VARCHAR(10),
Amount INT
)
INSERT INTO @tbl
(
SalesMan,
PayType,
Amount
)
VALUES
('Salesman A', 'Cash', 21151)
, ('Salesman B', 'Cash', 34510)
, ('Salesman C', 'Cash', 21252)
, ('Salesman D', 'Cash', 13356)
, ('Salesman A', 'Cheque', 13944)
, ('Salesman B', 'Cheque', 87368)
, ('Salesman C', 'Cheque', 20182)
, ('Salesman D', 'Cheque', 23862)
SELECT *
FROM
(
SELECT * FROM @tbl
)AS FooData
PIVOT(
AVG(FooData.Amount)
FOR PayType IN ([Cash], [Cheque])
) AS FooPivot
输出:
SalesMan Cash Cheque
Salesman A 21151 13944
Salesman B 34510 87368
Salesman C 21252 20182
Salesman D 13356 23862
答案 3 :(得分:2)
您可以通过以下方式旋转表格
With c as(
SELECT Salesman
, Paymode
, Sum(Collection) AS Cheque
FROM
Prospect_Detail
GROUP BY
Salesman
, Paymode
)
Select Salesman
,[Cash]
,[Cheque]
From C
Pivot(
Sum(Cheque)
For Paymode in ([Cash],[Cheque])
) as pvt;
我希望这对您有用。