I am having a tough time getting my crosstab query to execute. I keep getting "Duplicate Category Name Error 42710" when I run the following query.
SELECT
*
FROM
crosstab (
$$
Select
date_year,
city_size,
sum(Total_Rev)
From
(
SELECT
EXTRACT(YEAR FROM SOLD.DATE) Date_Year,
CASE WHEN CITY.POPULATION < 3700000 THEN 'SMALL' WHEN CITY.POPULATION >= 3700000
AND CITY.POPULATION < 6700000 THEN 'MEDIUM' WHEN CITY.POPULATION >= 6700000
AND CITY.POPULATION < 9000000 THEN 'LARGE' WHEN CITY.POPULATION >= 9000000 THEN 'X_LARGE' END City_Size,
CASE WHEN DISCOUNT_ON.DISCOUNT_PERCENTAGE IS NOT NULL THEN (
(DISCOUNT_ON.DISCOUNT_PERCENTAGE / 100) * PRODUCT.RETAIL_PRICE
) * SOLD.QUANTITY WHEN DISCOUNT_ON.DISCOUNT_PERCENTAGE IS NULL THEN PRODUCT.RETAIL_PRICE * SOLD.QUANTITY END Total_Rev
FROM
SOLD,
STORE,
CITY,
DISCOUNT_ON,
PRODUCT
WHERE
CITY.CITY_NAME = STORE.CITY_NAME
AND SOLD.PID = PRODUCT.PID
AND SOLD.PID = DISCOUNT_ON.PID
AND SOLD.DATE = DISCOUNT_ON.DATE
AND STORE.STORE_NUMBER = SOLD.STORE_NUMBER
) tbl1
group by
date_year,city_size
order by
date_year,city_size $$,
$$
SELECT
CASE WHEN CITY.POPULATION < 3700000 THEN 'SMALL' WHEN CITY.POPULATION >= 6700000
AND CITY.POPULATION < 9000000 THEN 'LARGE' END City_Size
FROM
CITY $$
) AS FINAL_RESULT(date_year Numeric,"SMALL" REAL,"MEDIUM" REAL,"LARGE" REAL,"X_LARGE" REAL );
When I run the subquery I do get results:
[Image of Results from Subquery]
Thank You
Using filtered aggregation is typically easier to deal with than using the crosstab() function:
select date_year,
sum(Total_Rev) filter (where city_size = 'SMALL') as small,
sum(Total_Rev) filter (where city_size = 'MEDIUM') as medium,
sum(Total_Rev) filter (where city_size = 'LARGE') as large,
sum(Total_Rev) filter (where city_size = 'X_LARGE') as x_large
from (
SELECT EXTRACT(YEAR FROM SOLD.DATE) Date_Year,
CASE
WHEN city.population < 3700000 THEN 'SMALL'
WHEN city.population >= 3700000 AND city.population < 6700000 then 'MEDIUM'
WHEN city.population >= 6700000 AND city.population < 9000000 then 'LARGE'
WHEN city.population >= 9000000 THEN 'X_LARGE'
END city_size,
CASE
WHEN DISCOUNT_ON.DISCOUNT_PERCENTAGE IS NOT NULL
THEN ((DISCOUNT_ON.DISCOUNT_PERCENTAGE / 100) * PRODUCT.RETAIL_PRICE) * SOLD.QUANTITY
WHEN DISCOUNT_ON.DISCOUNT_PERCENTAGE IS NULL
THEN PRODUCT.RETAIL_PRICE * SOLD.QUANTITY
END total_rev
FROM sold
JOIN store ON store.store_number = sold.store_number
JOIN city ON city.city_name = store.city_name
JOIN discount_on ON sold.pid = discount_on.pid AND sold.date = discount_on.date
JOIN product ON sold.pid = product.pid
) tbl1
group by date_year,city_size
order by date_year,city_size
This isn't my original query, it's one posted by a gentleman at http://elliot.land/. This is the script for the ELO Rating system. Problem with me is, I've tried and tried, but I don't know how to convert this POSTGRESQL (RECURSIVE) to TSQL (CTE). Anyone can help me with the conversion?
This is the data:
CREATE TABLE plays (
game_number INT NOT NULL, -- must be consecutive and start at 1!
p1name VARCHAR(255) NOT NULL, -- first player
p1score FLOAT NOT NULL, -- 0 or 1
p2name VARCHAR(255) NOT NULL, -- second player
p2score FLOAT NOT NULL -- 0 or 1
);
INSERT INTO plays VALUES
(1, 'Elliot', 0, 'Brendan', 1),
(2, 'Bob', 1, 'Brendan', 0),
(3, 'Bob', 1, 'Elliot', 0),
(4, 'Jane', 1, 'Bob', 0),
(5, 'Bob', 0, 'Brendan', 1),
(6, 'Jane', 1, 'Elliot', 0);
Here is the Formula where I need help with the conversion:
WITH RECURSIVE p(current_game_number) AS (
WITH players AS (
SELECT DISTINCT p1name AS player_name
FROM plays
UNION
SELECT DISTINCT p2name
FROM plays
)
SELECT
0 AS game_number,
player_name,
1000.0 :: FLOAT AS previous_elo,
1000.0 :: FLOAT AS new_elo
FROM players
UNION ALL
(
WITH previous_elos AS (
SELECT *
FROM p
)
SELECT
plays.game_number,
player_name,
previous_elos.new_elo AS previous_elo,
round(CASE WHEN player_name NOT IN (p1name, p2name)
THEN previous_elos.new_elo
WHEN player_name = p1name
THEN previous_elos.new_elo + 32.0 * (p1score - (r1 / (r1 + r2)))
ELSE previous_elos.new_elo + 32.0 * (p2score - (r2 / (r1 + r2))) END)
FROM plays
JOIN previous_elos
ON current_game_number = plays.game_number - 1
JOIN LATERAL (
SELECT
pow(10.0, (SELECT new_elo
FROM previous_elos
WHERE current_game_number = plays.game_number - 1 AND player_name = p1name) / 400.0) AS r1,
pow(10.0, (SELECT new_elo
FROM previous_elos
WHERE current_game_number = plays.game_number - 1 AND player_name = p2name) / 400.0) AS r2
) r
ON TRUE
)
)
SELECT
player_name,
(
SELECT new_elo
FROM p
WHERE t.player_name = p.player_name
ORDER BY current_game_number DESC
LIMIT 1
) AS elo,
count(CASE WHEN previous_elo < new_elo
THEN 1
ELSE NULL END) AS wins,
count(CASE WHEN previous_elo > new_elo
THEN 1
ELSE NULL END) AS losses
FROM
(
SELECT *
FROM p
WHERE previous_elo <> new_elo
ORDER BY current_game_number, player_name
) t
GROUP BY player_name
ORDER BY elo DESC;
SELECT
CASE WHEN SUM(X.Count)*3600 is null THEN '0'
ELSE
SUM(X.Count)*3600
END AS PJZ,
X.Mass
FROM X
WHERE X.Mass > 2000
HAVING ((X.Mass / PJZ * 100) - 100) >= 10;
Getting: ERROR: Column »pjz« doesn't exists.
How can I do something like this?
You can't use aliases in a having, and have to duplicate the statement in the having cluause. Since you only want to check for null, you could do this:
SELECT coalesce(SUM(X.Count)*3600, 0) AS PJZ, X.Mass
FROM X
WHERE X.Mass > 2000
HAVING ((X.Mass / coalesce(SUM(X.Count)*3600, 0) * 100) - 100) >= 10;
Other option is to surround query by WITH statement - for example:
WITH x as (
SELECT coalesce(SUM(X.Count)*3600, 0) AS PJZ, X.Mass
FROM X
WHERE X.Mass > 2000
)
SELECT * from X WHERE PJZ >=10
It is far better then code duplication in my opinion
Wrap it into a derived table:
SELECT CASE
WHEN PJZ = 0 THEN 100
ELSE PJZ
END as PJZ,
mass
FROM (
SELECT CASE
WHEN SUM(X.Count)*3600 is null THEN '0'
ELSE SUM(X.Count)*3600
END AS PJZ,
X.Mass
FROM X
WHERE X.Mass > 2000
GROUP BY X.mass
) t
WHERE PJZ = 0
OR ((X.Mass / PJZ * 100) - 100) >= 10;
(Note that I added the missing group by as otherwise the query would not be valid)
I have the following code which works FANTASTIC. Except - It is a sub-query to another (final) outer query and when I attempt to encapsulate this as a sub-query it refuses to run. To make it simple, I just did a "SELECT * FROM ( MY QUERY HERE)" and that even fails to run. I can only figure I am putting the right ")" in the wrong spot, but I just don't know....
Anyway - this is the query that runs fine till it is a simple sub-query:
SELECT FK_Campaign, FK_Geography, FK_InvoiceDate, FK_SalesType, FK_CustGroup, FK_Customer_Detail, FK_Parent_Detail, FK_Department, FK_Item_Detail,
FK_ItemClass_Detail, FK_ItemGroup_Detail, FK_SalesRep, FK_SalesOrigin, FK_QualityCode, FK_QualityDetailCode, FK_ResponsibilityCode,
FK_NewItemFlag, FK_TransDate, FK_CreatedDate, FK_VMReceivedDate, FK_ReturnAction, FK_StatusCode, ABC.InvoiceId, SalesID, VMRaNumber,
RetDays, ReturnQty, LineAmountmst, Qty, ReturnDays, ReturnLineAmount, ListPrice, ABC.InventTransId, ABC.ItemId,
ZZZ.FK_InventSerialProdDate AS FK_InventSerialProdDate
FROM
(SELECT
ISNULL((SELECT campaignkey --PK_Campaign
FROM VMDWAnalytical.DBO.DIM_Campaign
WHERE CampaignID = ST.smmCampaignID), -99) FK_Campaign,
ISNULL((SELECT PK_Geography
FROM VMDWAnalytical.DBO.DIM_Geography G
WHERE G.Country = ISNULL(CIJ.DLVCountryRegionID, 'zUnknown')
AND G.State = ISNULL(CIJ.DLVState, 'zUnknown')
AND G.Zip = ISNULL(CIJ.DLVZipCode, 'zUnknown')), -99) FK_Geography,
ISNULL((SELECT T.TIMEKEY
FROM VMDWAnalytical.DBO.DIM_Time T
WHERE T.FullDate = CIJ.InvoiceDate), 1) FK_InvoiceDate,
ISNULL((SELECT PK_SalesType
FROM VMDWAnalytical.DBO.DIM_SalesType
WHERE SalesType = SL.SalesType), -99) FK_SalesType,
ISNULL((SELECT PK_CustGroup
FROM VMDWAnalytical.DBO.DIM_CustGroup
WHERE CustGroup = CT.CustGroup), -99) FK_CustGroup,
ISNULL((SELECT PK_Customer_Detail
FROM VMDWAnalytical.DBO.DIM_Customer_Detail
WHERE AccountNum = CIJ.OrderAccount), -99) FK_Customer_Detail,
ISNULL((SELECT PK_Parent_Detail
FROM VMDWAnalytical.DBO.DIM_Parent_Detail
WHERE AccountNum = CIJ.OrderAccount), -99) FK_Parent_Detail,
ISNULL((SELECT PK_Department
FROM VMDWAnalytical.DBO.DIM_Department D
WHERE D.NUM = CIT.Dimension), -99) FK_Department,
ISNULL((SELECT PK_Item_Detail
FROM VMDWAnalytical.dbo.DIM_Item_Detail
WHERE Item = IT.ItemID
AND (ConfigID = ID.ConfigID
OR ConfigID = 'NONE')), -99) FK_Item_Detail,
ISNULL((SELECT PK_ItemClass_Detail
FROM VMDWAnalytical.dbo.DIM_ItemClass_Detail
WHERE ItemID = IT.ItemID), -99) FK_ItemClass_Detail,
ISNULL((SELECT PK_ItemGroup_Detail
FROM VMDWAnalytical.dbo.DIM_ItemGroup_Detail
WHERE ItemID = IT.ItemID), -99) FK_ItemGroup_Detail,
ISNULL((SELECT PK_SalesRep
FROM VMDWAnalytical.DBO.DIM_SalesRep
WHERE SalesRep = ST.SalesResponsible), -99) FK_SalesRep,
ISNULL((SELECT PK_SalesOrigin
FROM VMDWAnalytical.DBO.DIM_SalesOrigin
WHERE OriginID = ST.SalesOriginID), -99) FK_SalesOrigin,
CASE
WHEN CIT.Qty < 0 AND RR.TransDate IS NULL THEN
-97
WHEN CIT.QTY >=0 AND RR.TransDate IS NULL THEN
-98
ELSE
ISNULL((SELECT PK_QualityCode
FROM VMDWAnalytical.dbo.DIM_QualityCode
WHERE QualityCode = RR.VMQualityCode), -99)
END FK_QualityCode,
CASE
WHEN CIT.Qty < 0 AND RR.TransDate IS NULL THEN
-97
WHEN CIT.QTY >=0 AND RR.TransDate IS NULL THEN
-98
ELSE
ISNULL((SELECT PK_QualityDetailCode
FROM VMDWAnalytical.dbo.DIM_QualityDetailCode
WHERE QualityDetailCode = SL.VMQualityDetailCode
AND QualityCode = RR.VMQualityCode), -99)
END FK_QualityDetailCode,
CASE
WHEN CIT.Qty < 0 AND RR.TransDate IS NULL THEN
-97
WHEN CIT.QTY >=0 AND RR.TransDate IS NULL THEN
-98
ELSE
ISNULL((SELECT PK_ResponsibilityCode
FROM VMDWAnalytical.dbo.DIM_ResponsibilityCode
WHERE ResponsibilityCode = RR.VMResponsibilityCode), -99)
END FK_ResponsibilityCode,
CASE
WHEN ST.CREATEDDATE <= DATEADD(YEAR, 2, (SELECT KPISTARTDATE FROM RDS_KPIInventTableRel WHERE ITEMID = IT.ITEMID)) THEN
(SELECT PK_NEWITEMFLAG FROM VMDWAnalytical.DBO.DIM_NewItemFlag WHERE NewItemFlag = 'NEW')
ELSE
(SELECT PK_NEWITEMFLAG FROM VMDWAnalytical.DBO.DIM_NewItemFlag WHERE NewItemFlag = 'EXISTING')
END FK_NewItemFlag,
ISNULL((SELECT T.TIMEKEY
FROM VMDWAnalytical.DBO.DIM_Time T
WHERE T.FullDate = RR.TransDate), 1) FK_TransDate,
ISNULL((SELECT T.TIMEKEY
FROM VMDWAnalytical.DBO.DIM_Time T
WHERE T.FullDate = RR.CreatedDate), 1) FK_CreatedDate,
ISNULL((SELECT T.TIMEKEY
FROM VMDWAnalytical.DBO.DIM_Time T
WHERE T.FullDate = RR.VMReceivedDate), 1) FK_VMReceivedDate,
CASE
WHEN CIT.Qty < 0 AND RR.TransDate IS NULL THEN
-97
WHEN CIT.QTY >=0 AND RR.TransDate IS NULL THEN
-98
ELSE
ISNULL((SELECT PK_ReturnAction
FROM VMDWAnalytical.dbo.DIM_ReturnAction
WHERE ReturnActionID = RR.ReturnActionID), -99)
END FK_ReturnAction,
CASE
WHEN CIT.Qty < 0 AND RR.TransDate IS NULL THEN
-97
WHEN CIT.QTY >=0 AND RR.TransDate IS NULL THEN
-98
ELSE
ISNULL((SELECT PK_StatusCode
FROM VMDWAnalytical.dbo.DIM_StatusCode
WHERE StatusCode = RR.VMStatusCode), -99)
END FK_StatusCode,
ISNULL(CIT.InvoiceID, 'zUnknown') InvoiceID,
ISNULL(CIT.InventTransId, 'zUnknown') InventTransId,
ISNULL(CIT.ItemId, 'zUnknown') ItemId,
ISNULL(ST.SalesID, 'zUnknown') SalesID,
ISNULL(RR.VMRaNumber, 'zUnknown') VMRaNumber,
CASE
--A, Take out the Service item, flag with -98
WHEN IT.ITEMGROUPID = 'SERVICE' THEN
-98
--B, There is an original SO and the difference between the dates is non-negative
WHEN (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM) IS NOT NULL
AND DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM), ST.CREATEDDATE) >= 0 THEN
DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM), ST.CREATEDDATE)
--C, The last 10 characters of the refnum field start with SOR, and the orig SO date is not null and the difference between the dates is non-negative
WHEN RIGHT(ST.PURCHORDERFORMNUM, 10) LIKE 'SOR%' AND (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = RIGHT(ST.PURCHORDERFORMNUM, 10)) IS NOT NULL
AND DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = RIGHT(ST.PURCHORDERFORMNUM, 10)), ST.CREATEDDATE) >= 0 THEN
DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = RIGHT(ST.PURCHORDERFORMNUM, 10)), ST.CREATEDDATE)
--D, There is an original SO and the difference between the dates is negative
WHEN (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM) IS NOT NULL
AND DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM), ST.CREATEDDATE) < 0 THEN
DATEDIFF(DAY, (SELECT SCT.CAMPAIGNDATE FROM RDS_SMMCAMPAIGNTABLE SCT WHERE SCT.CAMPAIGNID = ST.SMMCAMPAIGNID), ST.CREATEDDATE)
--E, The last 10 characters of the refnum field start with SOR, and the orig SO date is not null, and the difference between the dates is negative
WHEN RIGHT(ST.PURCHORDERFORMNUM, 10) LIKE 'SOR%' AND (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = RIGHT(ST.PURCHORDERFORMNUM, 10)) IS NOT NULL
AND DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = RIGHT(ST.PURCHORDERFORMNUM, 10)), ST.CREATEDDATE) < 0 THEN
DATEDIFF(DAY, (SELECT SCT.CAMPAIGNDATE FROM RDS_SMMCAMPAIGNTABLE SCT WHERE SCT.CAMPAIGNID = ST.SMMCAMPAIGNID), ST.CREATEDDATE)
--F, If the campaign date <> 1/1/1900 and the datediff is positive
WHEN (SELECT SCT.CAMPAIGNDATE FROM RDS_SMMCAMPAIGNTABLE SCT WHERE SCT.CAMPAIGNID = ST.SMMCAMPAIGNID) <> '1/1/1900'
AND DATEDIFF(DAY, (SELECT SCT.CAMPAIGNDATE FROM RDS_SMMCAMPAIGNTABLE SCT WHERE SCT.CAMPAIGNID = ST.SMMCAMPAIGNID), ST.CREATEDDATE) >= 0 THEN
DATEDIFF(DAY, (SELECT SCT.CAMPAIGNDATE FROM RDS_SMMCAMPAIGNTABLE SCT WHERE SCT.CAMPAIGNID = ST.SMMCAMPAIGNID), ST.CREATEDDATE)
--G, If the difference between the Return SO and the Return and Repair transdate is positive
WHEN DATEDIFF(DAY, ST.CREATEDDATE, RR.TRANSDATE) > 0 THEN
DATEDIFF(DAY, ST.CREATEDDATE, RR.TRANSDATE)
--H
ELSE
-97
END RETDAYS,
--RETURNS
-1 * (CASE
WHEN SL.SALESTYPE = 4 THEN
CIT.LINEAMOUNTMST
ELSE
0
END) AS ReturnLineAmount,
-1 * (CASE
WHEN SL.SALESTYPE = 4 THEN
CIT.QTY
ELSE
0
END) AS ReturnQty,
--/RETURNS
(CIT.LINEAMOUNTMST) AS LineAmountMst, --Measure
(CIT.QTY) AS Qty, --Measure
ISNULL(DATEDIFF(DAY, RR.CreatedDate, RR.TransDate), 0) ReturnDays,
ITMS.PRICE AS ListPrice --Measure
FROM RDS_CUSTINVOICETRANS CIT
LEFT JOIN RDS_CUSTINVOICEJOUR CIJ
ON CIT.INVOICEID = CIJ.INVOICEID
JOIN RDS_CUSTTABLE CT
ON CIJ.ORDERACCOUNT = CT.ACCOUNTNUM
LEFT JOIN RDS_ADDRESSCOUNTRYREGION ACR
ON CIJ.DLVCOUNTRYREGIONID = ACR.COUNTRYREGIONID
LEFT JOIN RDS_SALESTABLE ST
ON CIJ.SALESID = ST.SALESID
LEFT JOIN RDS_SALESLINE SL
ON CIT.INVENTTRANSID = SL.INVENTTRANSID
LEFT JOIN RDS_INVENTTABLE IT
ON CIT.ITEMID = IT.ITEMID
LEFT JOIN RDS_INVENTTABLEMODULE ITMS
ON IT.ITEMID = ITMS.ITEMID
AND ITMS.MODULETYPE = 2
LEFT JOIN RDS_VMRETURNANDREPAIRTABLE RR
ON SL.SALESID = RR.SALESID
AND SL.VMRANUMBER = RR.VMRANUMBER
LEFT JOIN RDS_INVENTDIM ID
ON SL.INVENTDIMID = ID.INVENTDIMID
) ABC
--WHERE SL.SALESTYPE = 4 --and (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM) IS NULL
LEFT JOIN
(SELECT CIT.InventTransId AS InventTransId, CIT.ItemId AS ItemId, CIT.InvoiceId AS InvoiceId,
ISNULL((SELECT T.TIMEKEY
FROM VMDWANAlytical.DBO.DIM_Time T
WHERE T.FullDate = MAX(SR.ProdDate)),1) AS FK_InventSerialProdDate
FROM RDS_CustInvoiceTrans CIT
LEFT JOIN RDS_InventTrans IVT
ON CIT.InventTransId = IVT.InventTransId AND
CIT.InvoiceId = IVT.InvoiceId AND
CIT.ItemId = IVT.ItemId
LEFT JOIN RDS_INVENTDIM ID
ON IVT.InventDimId = ID.InventDimId
LEFT JOIN RDS_InventSerial SR
ON ID.InventSerialId = SR.InventSerialId AND
IVT.ItemId = SR.ItemId
GROUP BY CIT.InventTransId, CIT.ItemId, CIT.InvoiceId) ZZZ
ON ABC.InventTransId = ZZZ.InventTransId AND
ABC.ItemId = ZZZ.ItemId AND
ABC.InvoiceId = ZZZ.InvoiceId
I think you need to add an alias to the subquery so you'd have
SELECT * FROM ( MY QUERY HERE) as MyQuery
I'm trying to make the result of one of my subqueries be used in another subquery but it doesn't work.
This is the query:
SELECT t.TenantName,
(SELECT SUM(Amount)
FROM tblTransaction
WHERE Amount > 0
AND TransactionDate >= '12/01/09'
AND TransactionDate <= '12/31/09'
AND TenantID = t.ID
AND TransactionCode = trans.TransactionCode) AmountPaid,
(SELECT SUM(Amount)
FROM tblTransaction
WHERE tblTransaction.TransactionCode = trans.TransactionCode
AND tblTransaction.TenantID = t.ID) - AmountPaid AmountOwedTotal,
(SELECT SUM(Amount)
FROM tblTransaction
WHERE tblTransaction.TransactionCode = trans.TransactionCode
AND tblTransaction.TenantID = t.ID
AND Amount < 0 AND TransactionDate >= '12/01/09'
AND TransactionDate <= '12/31/09') AmountOwedThisMonth,
code.Description, trans.TransactionDate
FROM tblTransaction trans
LEFT JOIN tblTenantTransCode code
ON code.ID = trans.TransactionCode
LEFT JOIN tblTenant t
ON t.ID = trans.TenantID
WHERE trans.TransactionDate >= '12/01/09'
AND trans.TransactionDate <= '12/31/09'
AND trans.Amount > 0
Sorry it's so complicated.
Where I do (subquery) - AmountPaid the SqlServer complains AmountPaid isn't a valid column name. How can I get access to the result of it's subquery?
SELECT TenantName,
Description,
TransactionDate,
AmountPaid,
AmountRequired - AmountPaid AS AmountOwedTotal,
AmountOwedThisMonth
FROM (
SELECT t.TenantName,
code.Description,
trans.TransactionDate,
(
SELECT SUM(Amount)
FROM tblTransaction
WHERE Amount > 0
AND TransactionDate >= '12/01/09'
AND TransactionDate <= '12/31/09'
AND TenantID = t.ID
AND TransactionCode = trans.TransactionCode
) AS AmountPaid,
(
SELECT SUM(Amount)
FROM tblTransaction
WHERE tblTransaction.TransactionCode = trans.TransactionCode
AND tblTransaction.TenantID = t.ID
) AS AmountRequired,
(
SELECT SUM(Amount)
FROM tblTransaction
WHERE tblTransaction.TransactionCode = trans.TransactionCode
AND tblTransaction.TenantID = t.ID
AND Amount < 0
AND TransactionDate >= '12/01/09'
AND TransactionDate <= '12/31/09'
) AS AmountOwedThisMonth,
FROM tblTransaction trans
LEFT JOIN
tblTenantTransCode code
ON code.ID = trans.TransactionCode
LEFT JOIN
tblTenant t
ON t.ID = trans.TenantID
WHERE trans.TransactionDate >= '12/01/09'
AND trans.TransactionDate <= '12/31/09'
AND trans.Amount > 0
) q
try this:
Select t.TenantName, c.Description, tx.TransactionDate,
Sum(Case When TransactionDate Between '12/01/09' AND '12/31/09'
And Amount > 0
Then tx.Amount Else 0 End) AmountPaid,
Sum(tx.Amount) Total,
Sum(tx.Amount) -
Sum(Case When TransactionDate Between '12/01/09' AND '12/31/09'
And Amount > 0
Then tx.Amount Else 0 End) AnountOwed,
Sum(Case When TransactionDate Between '12/01/09' AND '12/31/09'
And Amount < 0
Then tx.Amount Else 0 End) AnountOwedThisMonth
FROM tblTransaction tx
LEFT JOIN tblTenantTransCode c
ON c.ID = tx.TransactionCode
LEFT JOIN tblTenant t
ON t.ID = tx.TenantID
Group By t.TenantName, c.Description