Using subquery alias in case - sql

I'm having hard time using a subquery alias in one of my CASE, after spending my time in documentation I cant find the solution on my own.
SELECT
t1.cardcode as Kundennummer,
t1.cardname,
t3.groupname,
(select
sum(t11.doctotal)as sum24
from
oinv t11
where
t11.cardcode=t1.cardcode
and t11.docduedate > dateadd(month, -24, getdate()) and t11.docduedate < dateadd(month, -12, getdate())
)as Umsatz24,
(select
sum(t10.doctotal) as sum12
from
oinv t10
where
t10.cardcode=t1.cardcode
and t10.docduedate > dateadd(month, -12, getdate())
)as Umsatz12,
case
when t3.groupname = 'C' and Umsatz12 = 0
then 'Dummy 0'
when t3.groupname = 'C' and Umsatz12 > 0
then 'Dummy 15'
when t3.groupname = 'B' and Umsatz24 = 0
then 'Dummy 15'
else
'Dummy 15/30?'
end as 'Dummy'
from
(... some code)
Any idea how I could fix it?
Thanks in advance.

You can use CTE for this.
;WITH T AS
(
SELECT
t1.cardcode as Kundennummer,
t1.cardname,
t3.groupname,
(select
sum(t11.doctotal)as sum24
from
oinv t11
where
t11.cardcode=t1.cardcode
and t11.docduedate > dateadd(month, -24, getdate()) and t11.docduedate < dateadd(month, -12, getdate())
)as Umsatz24,
(select
sum(t10.doctotal) as sum12
from
oinv t10
where
t10.cardcode=t1.cardcode
and t10.docduedate > dateadd(month, -12, getdate())
)as Umsatz12
from
(... some code)
)
SELECT *,
case
when groupname = 'C' and Umsatz12 = 0
then 'Dummy 0'
when groupname = 'C' and Umsatz12 > 0
then 'Dummy 15'
when groupname = 'B' and Umsatz24 = 0
then 'Dummy 15'
else
'Dummy 15/30?'
end as 'Dummy'
FROM T

I'd move the subqueries to the FROM clause and make this one query instead of two by using conditional aggregation:
select
t1.cardcode as kundennummer,
t1.cardname,
t3.groupname,
umsatz.umsatz24,
umsatz.umsatz12,
case
when t3.groupname = 'C' and umsatz.umsatz12 = 0 then 'Dummy 0'
when t3.groupname = 'C' and umsatz.umsatz12 > 0 then 'Dummy 15'
when t3.groupname = 'B' and umsatz.umsatz24 = 0 then 'Dummy 15'
else 'Dummy 15/30?'
end as dummy
from (... some code)
left join
(
select
cardcode,
sum(case when oinv.docduedate > dateadd(month, -24, getdate())
and oinv.docduedate < dateadd(month, -12, getdate())
then oinv.doctotal end) as umsatz24
sum(case when oinv.docduedate > dateadd(month, -12, getdate())
then oinv.doctotal end) as umsatz12
from oinv
group by cardcode
) umsatz on umsatz.cardcode = t1.cardcode;

You can use below approach.
you can execute and test the query here
select cc.CID,cc.CustomerName,cc.ContactName,cc.City,cc.Umsatz24,cc.Umsatz12,
case
when cc.City = 'London' and cc.Umsatz12 = 0
then 'Dummy 0'
when cc.City = 'London' and cc.Umsatz12 > 0
then 'Dummy 15'
when cc.City = 'Paris' and cc.Umsatz24 = 0
then 'Dummy 15'
else
'Dummy 15/30?'
end as 'Dummy'
from (
SELECT
t1.CustomerID as CID,
t1.CustomerName,
t1.ContactName,
t1.City,
(select
sum(t11.CustomerID)as sum24
from
Customers t11
where
t11.CustomerID=t1.CustomerID
and t11.City = 'Paris'
)as Umsatz24,
(select
sum(t10.CustomerID) as sum12
from
Customers t10
where
t10.CustomerID=t1.CustomerID
and t10.City = 'London'
)as Umsatz12
from Customers t1
) cc

Related

How can I include more columns other than just percentage column in my sql query result?

When I use the below query I only get percentage column but I want the (buyer_id, buyer_name, created_date,total_work_orders_with_gtv_first_60_days, total_gtv_first_60_days, total_net_amount_first_60_days) to show as columns too. Would really appreciate your help please.
WITH results_cte AS (
SELECT
b.buyer_id,
b.buyer_name,
CAST(b.created_date AS DATE) AS created_date,
COALESCE(wo.total_work_orders_with_gtv_first_60_days, 0) AS total_work_orders_with_gtv_first_60_days,
COALESCE(wo.total_gtv_first_60_days, 0) AS total_gtv_first_60_days,
COALESCE(wo.total_net_amount_first_60_days, 0) AS total_net_amount_first_60_days
FROM dw.buyer b
LEFT JOIN (SELECT wo.buyer_id,
COUNT(CASE WHEN wo.gtv_date < DATEADD(DAY, 60, b.created_date) THEN wo.work_order_id ELSE NULL END) AS total_work_orders_with_gtv_first_60_days,
SUM(CASE WHEN wo.gtv_date < DATEADD(DAY, 60, b.created_date) THEN wo.gtv ELSE NULL END) AS total_gtv_first_60_days,
SUM(CASE WHEN wo.gtv_date < DATEADD(DAY, 60, b.created_date) THEN wo.net_amount ELSE NULL END) AS total_net_amount_first_60_days
FROM dw.work_order wo
JOIN dw.buyer b
ON wo.buyer_id = b.buyer_id
WHERE wo.gtv > 0
GROUP BY wo.buyer_id) wo
ON b.buyer_id = wo.buyer_id
WHERE b.buyer_segmentation = 'S - Self-Service'
AND b.status = 'Active'
AND b.created_date >= DATEADD(YEAR, -1, GETDATE())
)
SELECT (SELECT CAST(count(DISTINCT buyer_id) AS float) FROM results_cte WHERE total_work_orders_with_gtv_first_60_days > 0)
/ (SELECT CAST(count(DISTINCT buyer_id) AS float) FROM results_cte ) AS percentage

COUNTing function output returns a different value than running slightly modified SQL directly

EDIT: DB is SQL Server 2008R2
So, essentially I'm having an issue where # of rows != count(*). Running this code:
SELECT *
FROM Fn_ForecastReport_TEST(NULL)
Returns 519 lines of output. But, running this code:
SELECT COUNT(*)
FROM Fn_ForecastReport_TEST(NULL)
Returns 502. This was extremely puzzling so I took the function's code:
CREATE FUNCTION dbo.Fn_ForecastReport_TEST(#Date DATE = NULL)
RETURNS #ForecastReportTable TABLE
(
InvcLine_SM NVARCHAR(155),
Cust_No NVARCHAR(15),
Cust_Name NVARCHAR(100),
Genus NVARCHAR(20),
S_City NVARCHAR(100),
[Default Whs] NVARCHAR(30),
U_CustChannel NVARCHAR(20),
[ActualKits-2] NUMERIC(38, 17),
[ActualKits-1] NUMERIC(38, 17),
ActualKits NUMERIC(38, 17),
[FC Kits] INT,
[FC Kits+1] INT,
[FC Kits+2] INT,
[FC Sales] NUMERIC(38, 6),
[FC Sales+1] NUMERIC(38, 6),
[FC Sales+2] NUMERIC(38, 6),
[Avg Price] NUMERIC(38, 6)
)
AS
BEGIN
-- If we provide NULL to the function, it will use today's date
SET #Date = ISNULL(#Date, GETDATE());
DECLARE
#TPlus2EndDate AS DATE,
#TPlus2StartDate AS DATE,
#TPlus1EndDate AS DATE,
#TPlus1StartDate AS DATE,
#TMinus0EndDate AS DATE,
#TMinus0StartDate AS DATE,
#TMinus1EndDate AS DATE,
#TMinus1StartDate AS DATE,
#TMinus2EndDate AS DATE,
#TMinus2StartDate AS DATE;
-- We use T Minus 0 as the basis for all other calculations so it needs to be calculated first
SELECT #TMinus0StartDate = FirstDay,
#TMinus0EndDate = LastDay
FROM Fn_GetFirstAndLastDaysOfMonthFromDate(#Date);
SELECT #TPlus2StartDate = FirstDay,
#TPlus2EndDate = LastDay
FROM Fn_GetFirstAndLastDaysOfMonthFromDate(DATEADD(MONTH, 2, #TMinus0StartDate));
SELECT #TPlus1StartDate = FirstDay,
#TPlus1EndDate = LastDay
FROM Fn_GetFirstAndLastDaysOfMonthFromDate(DATEADD(MONTH, 1, #TMinus0StartDate));
SELECT #TMinus1StartDate = FirstDay,
#TMinus1EndDate = LastDay
FROM Fn_GetFirstAndLastDaysOfMonthFromDate(DATEADD(MONTH, -1, #TMinus0StartDate));
SELECT #TMinus2StartDate = FirstDay,
#TMinus2EndDate = LastDay
FROM Fn_GetFirstAndLastDaysOfMonthFromDate(DATEADD(MONTH, -2, #TMinus0StartDate));
WITH Genera_CTE (Genus) AS (
SELECT '106' UNION ALL
SELECT '108' UNION ALL
SELECT '108YM' UNION ALL
SELECT '112' UNION ALL
SELECT '112XC' UNION ALL
SELECT '118'
),
SpecificPricesForEachBusinessPartnerByProductGenus AS (
SELECT T0.cardcode,
T1.U_Genus_Code,
sum((T1.U_NETcontents + 551) * T0.price) [Price]
FROM OSPP T0
INNER JOIN OITM T1 ON T0.ItemCode = T1.ItemCode
WHERE T0.price < 100
AND T1.U_Netcontents BETWEEN 450 AND 552
AND T1.Onhand <> 0
AND T1.U_Genus_Code IN (SELECT Genus FROM Genera_CTE)
GROUP BY T0.cardcode,
T1.U_Genus_Code
),
BestWarehouseForBusinessPartnerCity_CTE AS (
SELECT CardCode,
City,
U_Default_Whs
FROM CRD1
WHERE AdresType = 'S'
AND U_Default_Whs IS NOT NULL
GROUP BY CardCode,
City,
U_Default_Whs
),
MostRecentForecastsForPeriod AS (
SELECT *
FROM Fn_GetMostRecentForecastsForMonthOfDate(#Date)
UNION ALL
SELECT *
FROM Fn_GetMostRecentForecastsForMonthOfDate(#TPlus1StartDate)
UNION ALL
SELECT *
FROM Fn_GetMostRecentForecastsForMonthOfDate(#TPlus2StartDate)
),
ForecastsReformattedForReport AS (
SELECT T1.SlpName,
T0.U_Cust_ID,
T2.CardName,
T0.U_Genus,
T0.U_Ship_City,
'' [Dfl Whs],
T2.U_CustChannel [U_CustChannel],
0 [ActualKits],
0 [ActualKits-1],
0 [ActualKits-2],
SUM(CASE
WHEN T0.U_FC_Month BETWEEN #TMinus0StartDate AND #TMinus0EndDate
THEN T0.U_Sets
ELSE 0
END) [Forecast],
SUM(CASE
WHEN T0.U_FC_Month BETWEEN #TPlus1StartDate AND #TPlus1EndDate
THEN T0.U_Sets
ELSE 0
END) [Forecast+1],
SUM(CASE
WHEN T0.U_FC_Month BETWEEN #TPlus2StartDate AND #TPlus2EndDate
THEN T0.U_Sets
ELSE 0
END) [Forecast+2]
FROM MostRecentForecastsForPeriod T0
INNER JOIN OSLP T1 ON T0.U_SLP_ID = T1.SlpCode
INNER JOIN OCRD T2 ON T0.U_Cust_ID = T2.CardCode
WHERE T0.U_FC_Month BETWEEN #TMinus0StartDate AND #TPlus2EndDate
GROUP BY T1.SlpName,
T0.U_Cust_ID,
T2.CardName,
T0.U_Genus,
T0.U_Ship_City,
T2.U_CustChannel
),
ActualTransactionsFormattedForReport AS (
SELECT InvcLine_SM,
Cust_No,
Cust_Name,
Genus,
S_City,
CASE
WHEN U_Default_Whs IS NULL THEN 'Mesa Dflt'
ELSE U_Default_Whs
END AS 'Default Whs',
U_CustChannel,
SUM(CASE
WHEN Trx_Date BETWEEN #TMinus0StartDate AND #TMinus0EndDate
THEN Kits
ELSE 0
END) [ActualKits],
SUM(CASE
WHEN Trx_Date BETWEEN #TMinus1StartDate AND #TMinus1EndDate
THEN Kits
ELSE 0
END) [ActualKits-1],
SUM(CASE
WHEN Trx_Date BETWEEN #TMinus2StartDate AND #TMinus2EndDate
THEN Kits
ELSE 0
END) [ActualKits-2],
0 [Forecast],
0 [Forecast+1],
0 [Forecast+2]
FROM SWD_SALES_TRX
WHERE Genus IN (SELECT Genus FROM Genera_CTE)
AND Trx_Date BETWEEN #TMinus2StartDate AND #TMinus0EndDate
GROUP BY InvcLine_SM,
cust_no,
Cust_name,
U_Default_Whs,
Genus,
S_City,
U_CustChannel
),
TransactionsAndForecastsMergedForReport AS (
SELECT *
FROM ActualTransactionsFormattedForReport
UNION ALL
SELECT *
FROM ForecastsReformattedForReport
)
INSERT #ForecastReportTable
SELECT
T0.InvcLine_SM,
T0.Cust_No,
T0.Cust_Name,
T0.Genus,
T0.S_City,
CASE
WHEN MAX(A0.U_Default_Whs) = ''
OR MAX(A0.U_Default_Whs) IS NULL
THEN 'Mesa Dflt'
ELSE MAX(A0.U_Default_Whs)
END [Default Whs],
T0.U_CustChannel,
SUM(T0.[ActualKits-2]) [ActualKits-2],
SUM(T0.[ActualKits-1]) [ActualKits-1],
SUM(T0.[ActualKits]) [ActualKits],
Sum(T0.[Forecast]) [FC Kits],
Sum(T0.[Forecast+1]) [FC Kits+1],
Sum(T0.[Forecast+2]) [FC Kits+2],
SUM(T0.[Forecast]) * ISNULL(T5.Price, t6.total) [FC Sales],
SUM(T0.[Forecast+1]) * ISNULL(T5.Price, t6.total) [FC Sales+1],
SUM(T0.[Forecast+2]) * ISNULL(T5.Price, t6.total) [FC Sales+2],
MAX(T6.Total) [Avg Price]
FROM TransactionsAndForecastsMergedForReport T0
LEFT JOIN SpecificPricesForEachBusinessPartnerByProductGenus T5 ON T0.Cust_No = T5.CardCode
AND T5.U_Genus_Code = T0.Genus
LEFT JOIN (
SELECT T2.U_CustChannel,
T1.U_Genus_Code,
(CASE
WHEN SUM(CASE
WHEN T1.[InvntryUom] <> 'KIT'
THEN T0.Quantity
ELSE T0.Quantity * ISNULL(T1.U_NetContents, 1)
END) = 0
THEN 0
ELSE sum(T0.LineTotal) / SUM(CASE
WHEN T1.[InvntryUom] <> 'KIT'
THEN T0.Quantity
ELSE T0.Quantity * ISNULL(551 + T1.U_NetContents, 1)
END)
END) * (MAX(T1.U_NetContents) + 551) [Total]
FROM (
SELECT T0.CardCode,T1.LineTotal [LineTotal],T1.Quantity [Quantity],T1.ItemCode
FROM OINV T0
INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry
WHERE T0.Canceled = 'N'
AND (T1.LineTotal <> 0 OR TreeType = 'N')
UNION ALL
SELECT T0.CardCode,(T1.LineTotal) * -1 [LineTotal], -T1.Quantity [Quantity],T1.ItemCode
FROM ORIN T0
INNER JOIN RIN1 T1 ON T0.DocEntry = T1.DocEntry
WHERE T0.Canceled = 'N'
AND T0.docType <> 'S'
AND T0.CANCELED = 'N'
AND (T1.LineTotal <> 0 OR TreeType = 'N')
) T0
INNER JOIN OITM T1 ON T0.ItemCode = T1.ItemCode
INNER JOIN OCRD T2 ON T0.CardCode = T2.CardCode
WHERE T1.U_Netcontents BETWEEN 450 AND 552
AND t1.Onhand <> 0
AND (
T1.U_Genus_Code IN (SELECT Genus FROM Genera_CTE)
OR (T1.[InvntryUom] = 'KIT' AND T1.U_Genus_Code = '108')
)
GROUP BY T2.U_CustChannel,
T1.U_Genus_Code
) T6 ON T6.U_CustChannel = T0.U_CustChannel
AND T6.U_Genus_Code = T0.Genus
LEFT JOIN BestWarehouseForBusinessPartnerCity_CTE A0 ON A0.CardCode = T0.Cust_No
AND LOWER(A0.City) = LOWER(T0.S_City)
GROUP BY InvcLine_SM,
cust_no,
Cust_name,
genus,
S_City,
t5.price,
t6.total,
T0.U_CustChannel;
RETURN;
END
GO
I modified this SQL slightly so that it could be run outside of the function, and I noticed something extremely peculiar, which is the error goes away when I run it outside of the function:
-- If we provide NULL to the function, it will use today's date
DECLARE #Date DATE = GETDATE();
DECLARE
#TPlus2EndDate AS DATE,
#TPlus2StartDate AS DATE,
#TPlus1EndDate AS DATE,
#TPlus1StartDate AS DATE,
#TMinus0EndDate AS DATE,
#TMinus0StartDate AS DATE,
#TMinus1EndDate AS DATE,
#TMinus1StartDate AS DATE,
#TMinus2EndDate AS DATE,
#TMinus2StartDate AS DATE;
-- We use T Minus 0 as the basis for all other calculations so it needs to be calculated first
SELECT #TMinus0StartDate = FirstDay,
#TMinus0EndDate = LastDay
FROM Fn_GetFirstAndLastDaysOfMonthFromDate(#Date);
SELECT #TPlus2StartDate = FirstDay,
#TPlus2EndDate = LastDay
FROM Fn_GetFirstAndLastDaysOfMonthFromDate(DATEADD(MONTH, 2, #TMinus0StartDate));
SELECT #TPlus1StartDate = FirstDay,
#TPlus1EndDate = LastDay
FROM Fn_GetFirstAndLastDaysOfMonthFromDate(DATEADD(MONTH, 1, #TMinus0StartDate));
SELECT #TMinus1StartDate = FirstDay,
#TMinus1EndDate = LastDay
FROM Fn_GetFirstAndLastDaysOfMonthFromDate(DATEADD(MONTH, -1, #TMinus0StartDate));
SELECT #TMinus2StartDate = FirstDay,
#TMinus2EndDate = LastDay
FROM Fn_GetFirstAndLastDaysOfMonthFromDate(DATEADD(MONTH, -2, #TMinus0StartDate));
WITH Genera_CTE (Genus) AS (
SELECT '106' UNION ALL
SELECT '108' UNION ALL
SELECT '108YM' UNION ALL
SELECT '112' UNION ALL
SELECT '112XC' UNION ALL
SELECT '118'
),
SpecificPricesForEachBusinessPartnerByProductGenus AS (
SELECT T0.cardcode,
T1.U_Genus_Code,
sum((T1.U_NETcontents + 551) * T0.price) [Price]
FROM OSPP T0
INNER JOIN OITM T1 ON T0.ItemCode = T1.ItemCode
WHERE T0.price < 100
AND T1.U_Netcontents BETWEEN 450 AND 552
AND T1.Onhand <> 0
AND T1.U_Genus_Code IN (SELECT Genus FROM Genera_CTE)
GROUP BY T0.cardcode,
T1.U_Genus_Code
),
BestWarehouseForBusinessPartnerCity_CTE AS (
SELECT CardCode,
City,
U_Default_Whs
FROM CRD1
WHERE AdresType = 'S'
AND U_Default_Whs IS NOT NULL
GROUP BY CardCode,
City,
U_Default_Whs
),
MostRecentForecastsForPeriod AS (
SELECT *
FROM Fn_GetMostRecentForecastsForMonthOfDate(#Date)
UNION ALL
SELECT *
FROM Fn_GetMostRecentForecastsForMonthOfDate(#TPlus1StartDate)
UNION ALL
SELECT *
FROM Fn_GetMostRecentForecastsForMonthOfDate(#TPlus2StartDate)
),
ForecastsReformattedForReport AS (
SELECT T1.SlpName,
T0.U_Cust_ID,
T2.CardName,
T0.U_Genus,
T0.U_Ship_City,
'' [Dfl Whs],
T2.U_CustChannel [U_CustChannel],
0 [ActualKits],
0 [ActualKits-1],
0 [ActualKits-2],
SUM(CASE
WHEN T0.U_FC_Month BETWEEN #TMinus0StartDate AND #TMinus0EndDate
THEN T0.U_Sets
ELSE 0
END) [Forecast],
SUM(CASE
WHEN T0.U_FC_Month BETWEEN #TPlus1StartDate AND #TPlus1EndDate
THEN T0.U_Sets
ELSE 0
END) [Forecast+1],
SUM(CASE
WHEN T0.U_FC_Month BETWEEN #TPlus2StartDate AND #TPlus2EndDate
THEN T0.U_Sets
ELSE 0
END) [Forecast+2]
FROM MostRecentForecastsForPeriod T0
INNER JOIN OSLP T1 ON T0.U_SLP_ID = T1.SlpCode
INNER JOIN OCRD T2 ON T0.U_Cust_ID = T2.CardCode
WHERE T0.U_FC_Month BETWEEN #TMinus0StartDate AND #TPlus2EndDate
GROUP BY T1.SlpName,
T0.U_Cust_ID,
T2.CardName,
T0.U_Genus,
T0.U_Ship_City,
T2.U_CustChannel
),
ActualTransactionsFormattedForReport AS (
SELECT InvcLine_SM,
Cust_No,
Cust_Name,
Genus,
S_City,
CASE
WHEN U_Default_Whs IS NULL THEN 'Mesa Dflt'
ELSE U_Default_Whs
END AS 'Default Whs',
U_CustChannel,
SUM(CASE
WHEN Trx_Date BETWEEN #TMinus0StartDate AND #TMinus0EndDate
THEN Kits
ELSE 0
END) [ActualKits],
SUM(CASE
WHEN Trx_Date BETWEEN #TMinus1StartDate AND #TMinus1EndDate
THEN Kits
ELSE 0
END) [ActualKits-1],
SUM(CASE
WHEN Trx_Date BETWEEN #TMinus2StartDate AND #TMinus2EndDate
THEN Kits
ELSE 0
END) [ActualKits-2],
0 [Forecast],
0 [Forecast+1],
0 [Forecast+2]
FROM SWD_SALES_TRX
WHERE Genus IN (SELECT Genus FROM Genera_CTE)
AND Trx_Date BETWEEN #TMinus2StartDate AND #TMinus0EndDate
GROUP BY InvcLine_SM,
cust_no,
Cust_name,
U_Default_Whs,
Genus,
S_City,
U_CustChannel
),
TransactionsAndForecastsMergedForReport AS (
SELECT *
FROM ActualTransactionsFormattedForReport
UNION ALL
SELECT *
FROM ForecastsReformattedForReport
),
FinalOutput AS (
SELECT T0.InvcLine_SM,
T0.Cust_No,
T0.Cust_Name,
T0.Genus,
T0.S_City,
CASE
WHEN MAX(A0.U_Default_Whs) = ''
OR MAX(A0.U_Default_Whs) IS NULL
THEN 'Mesa Dflt'
ELSE MAX(A0.U_Default_Whs)
END [Default Whs],
T0.U_CustChannel,
SUM(T0.[ActualKits-2]) [ActualKits-2],
SUM(T0.[ActualKits-1]) [ActualKits-1],
SUM(T0.[ActualKits]) [ActualKits],
Sum(T0.[Forecast]) [FC Kits],
Sum(T0.[Forecast+1]) [FC Kits+1],
Sum(T0.[Forecast+2]) [FC Kits+2],
SUM(T0.[Forecast]) * ISNULL(T5.Price, t6.total) [FC Sales],
SUM(T0.[Forecast+1]) * ISNULL(T5.Price, t6.total) [FC Sales+1],
SUM(T0.[Forecast+2]) * ISNULL(T5.Price, t6.total) [FC Sales+2],
MAX(T6.Total) [Avg Price]
FROM TransactionsAndForecastsMergedForReport T0
LEFT JOIN SpecificPricesForEachBusinessPartnerByProductGenus T5 ON T0.Cust_No = T5.CardCode
AND T5.U_Genus_Code = T0.Genus
LEFT JOIN (
SELECT T2.U_CustChannel,
T1.U_Genus_Code,
(CASE
WHEN SUM(CASE
WHEN T1.[InvntryUom] <> 'KIT'
THEN T0.Quantity
ELSE T0.Quantity * ISNULL(T1.U_NetContents, 1)
END) = 0
THEN 0
ELSE sum(T0.LineTotal) / SUM(CASE
WHEN T1.[InvntryUom] <> 'KIT'
THEN T0.Quantity
ELSE T0.Quantity * ISNULL(551 + T1.U_NetContents, 1)
END)
END) * (MAX(T1.U_NetContents) + 551) [Total]
FROM (
SELECT T0.CardCode,T1.LineTotal [LineTotal],T1.Quantity [Quantity],T1.ItemCode
FROM OINV T0
INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry
WHERE T0.Canceled = 'N'
AND (T1.LineTotal <> 0 OR TreeType = 'N')
UNION ALL
SELECT T0.CardCode,(T1.LineTotal) * -1 [LineTotal], -T1.Quantity [Quantity],T1.ItemCode
FROM ORIN T0
INNER JOIN RIN1 T1 ON T0.DocEntry = T1.DocEntry
WHERE T0.Canceled = 'N'
AND T0.docType <> 'S'
AND T0.CANCELED = 'N'
AND (T1.LineTotal <> 0 OR TreeType = 'N')
) T0
INNER JOIN OITM T1 ON T0.ItemCode = T1.ItemCode
INNER JOIN OCRD T2 ON T0.CardCode = T2.CardCode
WHERE T1.U_Netcontents BETWEEN 450 AND 552
AND t1.Onhand <> 0
AND (
T1.U_Genus_Code IN (SELECT Genus FROM Genera_CTE)
OR (T1.[InvntryUom] = 'KIT' AND T1.U_Genus_Code = '108')
)
GROUP BY T2.U_CustChannel,
T1.U_Genus_Code
) T6 ON T6.U_CustChannel = T0.U_CustChannel
AND T6.U_Genus_Code = T0.Genus
LEFT JOIN BestWarehouseForBusinessPartnerCity_CTE A0 ON A0.CardCode = T0.Cust_No
AND LOWER(A0.City) = LOWER(T0.S_City)
GROUP BY InvcLine_SM,
cust_no,
Cust_name,
genus,
S_City,
t5.price,
t6.total,
T0.U_CustChannel
)
SELECT count(*)
FROM FinalOutput;
Essentially, the only changes are switching #Date to a DECLARE rather than SET, along with removing the INSERT for the function output. Is there some quirk with functions that causes the count to return a value different than the actual number of rows?
This is a problem with JetBrain's DataGrip product. When I ran the same code in SSMS it returned the proper amount for the COUNT.
SQL Server, at times, has inaccurate information the sys.sysindexes table/view...try to update your indexes and statistics and see if it's still non-matching.
if it is cleared up, then the count(*) was pulling it's row counts out of the indexes instead of the tables while the select returned the actual rows.
nvm, jetbrain did it! how wude!!

Use a date based on field value

I need to find a way to relate two sets of orders. Essentially, and inbound versus outbound analysis for a report. A load balance to see when I need to organize more pickups or deliveries.
I need to pull the delivery_date when billing_group = 3
I need to pull the origin_date when billing_group = 4
Hope this made some sense. Thank you all!
select convert(varchar,Delivery_Date,101) as 'Delivery_Date',
convert(varchar,Origin_Date,101) as 'Origin_Date',
sum(case when billing_group = '3' then 1 else 0 end) as 'OR to WA',
sum(case when billing_group = '4' then 1 else 0 end) as 'WA to OR',
count(*) as Total_Orders
from orders
where Date >= dateadd(day, datediff(day, 0, GetDate()) - 30, 0) and
billing_group in ('3','4')
group by Date
order by date desc
Would it be possible to combine these two separate queries into one to provide a the following columns? date, OR to WA, and WA to OR (like in the example above) where the date (regardless of origin or delivery date is used
select convert(varchar,Delivery_Date,101) as 'Date',
sum(case when billing_group = '3' and delivery_date >= dateadd(day,datediff(day, 0, GetDate()) - 30, 0) then 1 else 0 end) as 'OR to WA'
from orders
where delivery_Date >= dateadd(day, datediff(day, 0, GetDate()) - 20, 0) and billing_group in ('3')
group by delivery_date
order by date desc
select convert(varchar,Origin_Date,101) as 'Date',
sum(case when billing_group = '4' and origin_date >= dateadd(day, datediff(day, 0, GetDate()) - 30, 0)then 1 else 0 end) as 'WA to OR'
from orders
where origin_Date >= dateadd(day, datediff(day, 0, GetDate()) - 20, 0) and billing_group in ('4')
group by origin_Date
order by date desc
I think you need to group by convert(varchar,Delivery_Date,101) instead of date.
When you use aggregate function you need to add non-aggregate colunms in group by.
select convert(varchar,Delivery_Date,101) as 'Delivery_Date',
sum(case when billing_group = '3' then 1 else 0 end) as 'OR to WA',
sum(case when billing_group = '4' then 1 else 0 end) as 'WA to OR',
count(*) as Total_Orders
from orders
where Date >= dateadd(day, datediff(day, 0, GetDate()) - 30, 0) and
billing_group in ('3','4')
group by convert(varchar,Delivery_Date,101)
order by date desc
EDIT
I saw you edit your question, you can try to use UNION ALL
SELECT * FROM (
select convert(varchar,Delivery_Date,101) as 'Date',
sum(case when billing_group = '3' and delivery_date >= dateadd(day,datediff(day, 0, GetDate()) - 30, 0) then 1 else 0 end) as 'OR to WA'
from orders
where delivery_Date >= dateadd(day, datediff(day, 0, GetDate()) - 20, 0) and billing_group in ('3')
group by delivery_date
UNION ALL
select convert(varchar,Origin_Date,101) as 'Date',
sum(case when billing_group = '4' and origin_date >= dateadd(day, datediff(day, 0, GetDate()) - 30, 0)then 1 else 0 end) as 'WA to OR'
from orders
where origin_Date >= dateadd(day, datediff(day, 0, GetDate()) - 20, 0) and billing_group in ('4')
group by origin_Date
) t1
ORDER BY Date desc

case on join criteria possible

Here is my query:
select
case when m.current0 < 25000 then 'Limited' else 'Unlimited' end,
m.current0 as CurrentBalance,
m.status as CurrentStatus,
sh.datechanged as EntertedPA6,
datediff(d, sh.datechanged, getdate()) as DaysPassed
from StatusHistory sh
inner join master m
on m.number = sh.accountid
and sh.newstatus = 'pa6'
and sh.datechanged <= DATEADD(day, -20, GETDATE())
and m.status = 'pa6'
and m.state = 'ca'
Similar to the case statement in the first line of the select. I need something similar on the join criteria.
If m.current0 < 25000 then sh.datechanged <= DATEADD(day, -20, GETDATE())
If m.current0 > 25000 then sh.datechanged <= DATEADD(day, -90, GETDATE())
Is this possible or do I need to do a union all?
Using ORs and ANDs you could do something like
select
case when m.current0 < 25000 then 'Limited' else 'Unlimited' end
,m.current0 as CurrentBalance
,m.status as CurrentStatus
,sh.datechanged as EntertedPA6
,datediff(d, sh.datechanged, getdate()) as DaysPassed
from StatusHistory sh
inner join master m on m.number = sh.accountid and sh.newstatus = m.status
WHERE m.status = 'pa6' AND m.state = 'ca' AND
((m.current0 < 25000 AND sh.datechanged <= DATEADD(day, -20, GETDATE()))
OR (m.current0 >= 25000 AND sh.datechanged <= DATEADD(day, -90, GETDATE())))

How to improve the performance of this query that spans across multiple databases?

here is my query taking nearly 20 mins. pls suggest me changes to increase performance
SELECT DISTINCT
CONVERT(varchar(10),x.notice_date,120) Date,
Y.branch_name,
count(case when x.status='broken' and x.branch_name=y.branch_name then 1 end)
Broken,
count(case when x.type='Lote' and x.branch_name=y.branch_name then 1 end)
Lost,
( SELECT COUNT(A.car_no)
FROM DB2.dbo.z_mat A
WHERE DateAdd(Day, DateDiff(Day, 0,a.notice_date), 0)
= DateAdd(Day, DateDiff(Day, 0,x.notice_date), 0)
AND a.branch_name=y.branch_name
) mat,
( SELECT COUNT(B.car_no)
FROM DB2.dbo.z_cat B
WHERE DateAdd(Day, DateDiff(Day, 0,b.notice_date), 0)
= DateAdd(Day, DateDiff(Day, 0,x.notice_date), 0)
AND b.branch_name=y.branch_name
) cat,
( SELECT COUNT(C.car_no)
FROM DB2.dbo.z_pat C
WHERE DateAdd(Day, DateDiff(Day, 0,c.notice_date), 0)
= DateAdd(Day, DateDiff(Day, 0,x.notice_date), 0)
AND c.branch_name=y.branch_name
) pat
FROM DB1.dbo.Cars x
, DB2.dbo.Branch Y
WHERE DateAdd(Day, DateDiff(Day, 0,x.notice_date), 0)
> '2011-01-01'
GROUP BY CONVERT(varchar(10),x.notice_date,120)
, DateAdd(Day, DateDiff(Day, 0,x.notice_date), 0)
, y.branch_name
This might help. Give it a try.
SELECT
DISTINCT CONVERT(VARCHAR(10), car.notice_date, 120) AS NoticeDate
, brc.branch_name
, COUNT(CASE WHEN car.status = 'broken' AND car.branch_name = brc.branch_name THEN 1 END) Broken
, COUNT(CASE WHEN car.status = 'Lote' AND car.branch_name = brc.branch_name THEN 1 END) Lost
, mat.mat_count
, cat.cat_count
, pat.pat_count
FROM DB1.dbo.Cars car
, DB2.dbo.Branch brc
CROSS APPLY (
SELECT COUNT(mat.car_no) mat_count
FROM DB2.dbo.z_mat mat
WHERE DATEDIFF(d, mat.notice_date, car.notice_date) = 0
AND mat.branch_name = brc.branch_name
) mat
CROSS APPLY (
SELECT COUNT(cat.car_no) cat_count
FROM DB2.dbo.z_cat cat
WHERE DATEDIFF(d, cat.notice_date, car.notice_date) = 0
AND cat.branch_name = brc.branch_name
) cat
CROSS APPLY (
SELECT COUNT(pat.car_no) pat_count
FROM DB2.dbo.z_pat pat
WHERE DATEDIFF(d, pat.notice_date, car.notice_date) = 0
AND pat.branch_name = brc.branch_name
) pat
WHERE car.notice_date > '2011-01-01'
GROUP BY CONVERT(VARCHAR(10), car.notice_date, 120)
, brc.branch_name
SELECT CONVERT(varchar(10),x.notice_date,120) Date,Y.branch_name,
COUNT(case when x.status='broken' then 1 end) Broken,
COUNT(case when x.type='Lote' then 1 end) Lost,
SUM(mat) mat, SUM(cat) cat,SUM(pat) pat
FROM DB1.dbo.Cars x
JOIN DB2.dbo.Branch Y ON x.branch_name=y.branch_name
-- group by date and branch name for z_mat table
LEFT JOIN (select COUNT(car_no) mat,branch_name,DateAdd(Day, DateDiff(Day,notice_date), 0)) notice_date from DB2.dbo.z_mat GROUP BY branch_name,DateAdd(Day, DateDiff(Day,notice_date), 0)) AS a
ON a.branch_name = y.branch_name AND DateAdd(Day, DateDiff(Day, 0,x.notice_date), 0) = a.notice_date
-- group by date and branch name for z_cat table
LEFT JOIN (select COUNT(car_no) cat,branch_name,DateAdd(Day, DateDiff(Day,notice_date), 0)) notice_date from DB2.dbo.z_cat GROUP BY branch_name,DateAdd(Day, DateDiff(Day,notice_date), 0)) AS b
ON b.branch_name = y.branch_name AND DateAdd(Day, DateDiff(Day, 0,x.notice_date), 0) = b.notice_date
-- group by date and branch name for z_pat table
LEFT JOIN (select COUNT(car_no) pat,branch_name,DateAdd(Day, DateDiff(Day,notice_date), 0)) notice_date from DB2.dbo.z_pat GROUP BY branch_name,DateAdd(Day, DateDiff(Day,notice_date), 0)) AS c
ON c.branch_name = y.branch_name AND DateAdd(Day, DateDiff(Day, 0,x.notice_date), 0) = c.notice_date
WHERE DateAdd(Day, DateDiff(Day, 0,x.notice_date), 0)>'2011-01-01'
GROUP BY CONVERT(varchar(10),x.notice_date,120),DateAdd(Day, DateDiff(Day, 0,x.notice_date), 0),y.branch_name