您好我有SQL脚本并尝试添加具有不同条件的额外列但无法使其工作。
Select
PUB_Name As 'Pub Name'
,SUM(PUB_Collected) AS Collected
,Sum(PUB_Loyalty) As SumLoyalty
,(CASE WHEN SUM(PUB_Collected)>0 THEN (SUM(PUB_Loyalty)/SUM(PUB_Collected))ELSE NULL END) AS 'Percentage'
,SUM(PUB_Lodged_To_Till) As SumLodged
,Sum(PUB_Paid_Out) As SumPaidOut
,SUM(PUB_Lodged_To_Till) - Sum(PUB_Paid_Out) As 'Profit/Lose'
,SUM(PUB_Lodged_To_Till) - SUM(PUB_Paid_Out) - SUM(PUB_Loyalty) As 'Profit/Lose + Loyalty'
FROM [MattPubsDB].[dbo].[PUBRecords]
WHERE PUB_Date >= '2015-03-01'AND PUB_Date < '2015-06-01'
Group By PUB_Name
我想得到这个专栏:
,SUM(PUB_Lodged_To_Till) - SUM(PUB_Paid_Out) - SUM(PUB_Loyalty) As 'Profit/Lose + Loyalty 2nd'
与不同的WHERE:
WHERE PUB_Date >= '2015-01-01'AND PUB_Date < '2015-06-01'
当我开始学习SQL时,我将不胜感激。
答案 0 :(得分:0)
您将不得不使用条件聚合,这将影响您的所有聚合。查询将如下所示:
Select PUB_Name As `Pub Name`,
SUM(CASE WHEN PUB_Date >= '2015-03-01'AND PUB_Date < '2015-06-01' THEn PUB_Collected ELSE 0 END) AS Collected,
. . .
SUM(CASE WHEN PUB_Date >= '2015-01-01'AND PUB_Date < '2015-06-01'
THEN COALESCE(PUB_Lodged_To_Till, 0) - COALESCE(PUB_Paid_Out, 0) - COALESCE(PUB_Loyalty, 0)
ELSE 0
END) As `Profit/Lose + Loyalty 2nd`
FROM [MattPubsDB].[dbo].[PUBRecords]
Group By PUB_Name;
我建议你更改列别名,这样就不需要对它们进行转义(例如,没有空格)。如果您不想更改名称,请使用后退标记。尽管允许使用单引号,但它们往往会导致混淆,因为在其他任何地方都不允许使用列别名。