How to convert T-SQL Script to CTE for Snowflake / DBT - sql-server

I'm having trouble converting my TSQL Script into CTE that needs to be run on Snowflake through DBT model.
declare #i integer = 1
declare #LastID varchar(38) = ''
declare #Change money
declare #ID varchar(38)
declare #TranTypeID varchar(38)
declare #RunningLateFees money = 0
declare #RunningOtherFees money = 0
declare #Temp money = 0
select #ID = ID, #TranTypeID = TranTypeID, #Change = Change from Transactions where Seq = #i
while #ID is not null
begin
if #ID <> #LastID
begin
set #LastID = #ID
set #RunningLateFees = 0
set #RunningOtherFees = 0
end
if #Change > 0
begin
if #TranTypeID in ('Type1', 'Type2')
set #RunningLateFees = #RunningLateFees + #Change
else
set #RunningOtherFees = #RunningOtherFees + #Change
end
else
begin
set #Temp = #RunningLateFees
set #RunningLateFees = case when #RunningLateFees > abs(#Change) then #RunningLateFees + #Change else 0 end
set #Temp = #Change + (#Temp - #RunningLateFees)
set #RunningOtherFees = case when #RunningOtherFees > abs(#Temp) then #RunningOtherFees + #Change else 0 end
end
update Transactions set LateFees = #RunningLateFees, OtherFees = #RunningOtherFees where Seq = #i
set #i = #i + 1
set #ID = null
select #ID = ID, #TranTypeID = TranTypeID, #Change = Change from Transactions where Seq = #i
end
When I started out initally, I converted this into a macro within my DBT project.
{% macro update_transactions() %}
execute immediate $$
declare
sequence integer default 1;
var_ID varchar;
var_TranTypeID varchar;
var_Change varchar;
var_LastID varchar default '';
var_RunningLateFees number(38,4);
var_RunningOtherFees number(38,4);
var_Temp number(38,4);
res resultset;
begin
let counter := :sequence;
select ID, TranTypeID, Change into :var_ID, :var_TranTypeID, :var_Change FROM {{ this }} where Seq = :counter;
while (:var_ID IS NOT NULL) do
IF (:var_ID <> :var_LastID) THEN
var_LastID := :var_ID;
var_RunningLateFees := 0;
var_RunningOtherFees := 0;
END IF;
IF (:var_Change > 0) THEN
IF (:var_TranTypeID IN ('Type1', 'Type2')) THEN
var_RunningLateFees := :var_RunningLateFees + :var_Change;
ELSE
var_RunningOtherFees := :var_RunningOtherFees + :var_Change;
END IF;
ELSE
var_Temp := :var_RunningLateFees;
var_RunningLateFees := case when :var_RunningLateFees > abs(:var_Change) then :var_RunningLateFees + :var_Change else 0 end;
var_Temp := :var_Change + (:var_Temp - :var_RunningLateFees);
var_RunningOtherFees := case when :var_RunningOtherFees > abs(:var_Temp) then :var_RunningOtherFees + :var_Change else 0 end;
END IF;
update {{ this }} set LateFees = :var_RunningLateFees, OtherFees = :var_RunningOtherFees where Seq = :counter;
counter := counter + 1;
var_ID := NULL;
select ID, TranTypeID, Change into :var_ID, :var_TranTypeID, :var_Change FROM {{ this }} where Seq = :counter;
end while;
end;
$$
;
{% endmacro %}
However, due to Snowflake's implementation of data as micro-partitions in cloud storage, this approach was not recommended and the updates were too slow. It took about 10mins for 1000 records to update.
I went back to the drawing board trying to convert this into a CTE or SQL with Window functions. Haven't really been successful so far in this endeavour.
Greatly appreciate any help here.
This how my data looks like:
Seq
Change
TranID
TranTypeID
ID
LateFees
OtherFees
1
2.75
97c2a7
Type3
b69
null
null
2
25
ec0620
Type1
b69
null
null
3
-27.75
a5a44d
Type3
b69
null
null
4
2.75
8c6b32
Type3
b69
null
null
5
-2.75
97c2a7
Type3
b69
null
null
6
2.75
010bfe
Type3
b69
null
null
7
2.75
010bfb
Type3
73a
null
null
8
25
e499ad
Type1
73a
null
null
9
2.75
e6b37e
Type3
73a
null
null
10
25
464e7a
Type1
73a
null
null
11
2.75
4e1b7f
Type3
73a
null
null
12
25
944c75
Type1
73a
null
null
13
2.75
9e4851
Type3
73a
null
null
14
2.75
9e485a
Type3
73a
null
null
15
25
436da8
Type1
73a
null
null
16
2.75
446ce4
Type3
73a
null
null
17
25
4307e1
Type1
73a
null
null
18
2.75
164de2
Type3
73a
null
null
19
-144.25
bff6c7
Type3
73a
null
null
Desired Output:
Seq
Change
TranID
TranTypeID
ID
LateFees
OtherFees
1
2.75
97c2a7
Type3
b69
0.00
2.75
2
25
ec0620
Type1
b69
25.00
2.75
3
-27.75
a5a44d
Type3
b69
0.00
0.00
4
2.75
8c6b32
Type3
b69
0.00
2.75
5
-2.75
97c2a7
Type3
b69
0.00
0.00
6
2.75
010bfe
Type3
b69
0.00
2.75
7
2.75
010bfb
Type3
73a
0.00
2.75
8
25
e499ad
Type1
73a
25.00
2.75
9
2.75
e6b37e
Type3
73a
25.00
5.50
10
25
464e7a
Type1
73a
50.00
5.50
11
2.75
4e1b7f
Type3
73a
50.00
8.25
12
25
944c75
Type1
73a
75.00
8.25
13
2.75
9e4851
Type3
73a
75.00
11.00
14
2.75
9e485a
Type3
73a
75.00
13.75
15
25
436da8
Type1
73a
100.00
13.75
16
2.75
446ce4
Type3
73a
100.00
16.50
17
25
4307e1
Type1
73a
125.00
16.50
18
2.75
164de2
Type3
73a
125.00
19.25
19
-144.25
bff6c7
Type3
73a
0.00
0.00
EDIT: The SQL I have built that isn't getting me the result I need:
select
Seq,
Change,
TranID,
TranTypeID,
ID,
SUM(IFNULL(LateFees,0)) OVER (partition by ID order by Seq) as RunningTotalLateFees,
SUM(IFNULL(OtherFees,0)) OVER (partition by ID order by Seq) as RunningTotalOtherFees,
CASE
WHEN Change > 0 AND TranTypeID in ('Type1', 'Type2')
THEN RunningTotalLateFees + Change
WHEN Change <= 0
THEN case when RunningTotalLateFees > abs(Change) then RunningTotalLateFees + Change else 0 end
ELSE 0
END as LateFees,
CASE
WHEN Change > 0 AND TranTypeID NOT in ('Type1', 'Type2')
THEN RunningTotalOtherFees + Change
WHEN Change <= 0
THEN case when RunningTotalOtherFees > abs(Change + RunningTotalLateFees - LateFees) then RunningTotalOtherFees + Change else 0 end
ELSE 0
END as OtherFees
from Transactions
Order by Seq
What am I doing wrong here?

There is a circular reference in your SQL, where RunningTotalLateFees refers to LateFees. You can simplify this quite a bit by using greatest to keep LateFees nonnegative:
select
Seq,
Change,
TranID,
TranTypeID,
ID,
SUM(
case
when TranTypeID in ('Type1', 'Type2')
then Change
end
) OVER (
partition by ID
order by Seq
rows between unbounded preceding and current row
) as RunningTotalLateFees,
GREATEST(RunningTotalLateFees, 0) as LateFees,
SUM(
case
when TranTypeID NOT in ('Type1', 'Type2')
then Change
end
) OVER (
partition by ID
order by Seq
rows between unbounded preceding and current row
) as RunningTotalOtherFees,
GREATEST(RunningTotalOtherFees, 0) as OtherFees
from Transactions
Order by Seq

Related

T SQL Cursor is only updating row with same value

I'm using MS SQL Server and I have the below table 'tmp_AVG_Weekly_Sales':
RowID SKU Shop Week Avg_Value LAMBDA PMF Value
1 ABC 200 2 1 2 0.13 NULL
2 DEF 250 2 2 4 0.018 NULL
3 XYZ 300 3 3 6 0.0024 NULL
I need to work out the Value field based on the below logic - I am using a Cursor and Loop:
DECLARE #CUMULATIVE AS FLOAT = 0;
DECLARE #COUNT AS INT = 0;
DECLARE #LAMBDA AS FLOAT;
DECLARE #RowID AS INT;
DECLARE #PoissonCursor AS CURSOR;
DECLARE #THRESHOLD AS FLOAT = 0.99;
DECLARE #PMF AS FLOAT --= EXP(-#LAMBDA)
SET #PoissonCursor = CURSOR FOR
SELECT RowID
FROM
[tmp_AVG_Weekly_Sales]
OPEN #PoissonCursor;
FETCH NEXT FROM #PoissonCursor INTO #RowID;
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #LAMBDA = LAMBDA FROM [tmp_AVG_Weekly_Sales] WHERE RowID = #RowID
SELECT #PMF = PMF FROM [tmp_AVG_Weekly_Sales] WHERE RowID = #RowID
WHILE (#CUMULATIVE < #Threshold)
BEGIN
SET #CUMULATIVE += #PMF
SET #COUNT += 1
SET #PMF = #PMF * (#LAMBDA / #COUNT)
END
UPDATE [tmp_AVG_Weekly_Sales] SET [Value] = #COUNT - 1 WHERE RowID = #RowID
FETCH NEXT FROM #PoissonCursor INTO #RowID;
END
However, the above is just populating the Value field with the same value:
RowID SKU Shop Week Avg_Value LAMBDA PMF Value
1 ABC 200 2 1 2 0.13 6
2 DEF 250 2 2 4 0.018 6
3 XYZ 300 3 3 6 0.0024 6
When I am expecting the below:
RowID SKU Shop Week Avg_Value LAMBDA PMF Value
1 ABC 200 2 1 2 0.13 6
2 DEF 250 2 2 4 0.018 9
3 XYZ 300 3 3 6 0.0024 12
Where am I going wrong?
You never reset #CUMULATIVE or increase #Threshold, so the block of SET calls are only executed the first go through and each subsequent UPDATE just uses those original values.

How to Group Items in a Count statement

I'm trying to create a query that will return Total Claims reported in 0-3 days, 4-7 days, 8-14 days, and 15+
Select DATEDiff(DD,LossDate,DateReported) As TimeToReport,Count(ClaimId) As Num from LossRun
where PolicyNum='1234567890'
And PolTerm='201403'
Group By DATEDiff(DD,LossDate,DateReported)
order by DATEDiff(DD,LossDate,DateReported);
This is what i get
TimeToReport NumofClaims
0 5
1 3
2 1
3 4
4 3
5 2
6 2
7 2
8 1
12 1
13 1
14 2
15 2
48 1
52 1
107 1
121 1
147 1
533 1
Basically i want to see the total for 0-3, 4-7,8-14,and the rest,,,, timeToReport
You can try to use SUM with CASW WHEN
select
SUM(CASW WHEN TimeToReport <= 3 THEN NumofClaims ELSE 0 END) '0~3 day',
SUM(CASW WHEN TimeToReport >= 4 AND TimeToReport <=7 THEN NumofClaims END) '4-7 days',
SUM(CASW WHEN TimeToReport >= 8 AND TimeToReport <=14 THEN NumofClaims ELSE 0 END) '8-14 days',
SUM(CASW WHEN TimeToReport >= 15 THEN NumofClaims ELSE 0 END) '15+ day'
from (
Select DATEDiff(DD,LossDate,DateReported) As TimeToReport,Count(ClaimId) As Num
from LossRun
where PolicyNum='1234567890'
And PolTerm='201403'
Group By DATEDiff(DD,LossDate,DateReported)
) t
The most simple way is going to be by creating your own temp table which includes the min and max for each bucket and then joining to it.
declare #t table (OrderedID int, EmpID int, EffDate date, Salary money)
insert into #t
values
(1,1234,'20150101',1)
,(2,1234,'20160101',2)
,(3,1234,'20170101',8)
,(4,1234,'20180101',15)
,(1,2351,'20150101',17)
,(5,1234,'20190101',4)
,(5,1234,'20190101',2)
,(5,1234,'20190101',9)
declare #Bin table (MinVal int, MaxVal int)
insert into #Bin
values
(1,3)
,(4,6)
,(7,9)
,(10,15)
,(15,20)
,(20,25)
Select
B.MinVal,count(T.EmpID) as EmpsInBin
From #t T
inner join #Bin B on T.Salary between B.MinVal and B.MaxVal
group by B.MinVal
Output
MinVal EmpsInBin
1 3
4 1
7 2
10 1
15 2

Logical lock in WHERE clause

Since FUNCCODE is shared between POSCODE and DEVCODE I can't call out both at the same time to eliminate the null values to insert the data into a separate table called JOINT. POSCODE and DEVCODE are FKs. I know there has to be a much easier way of doing this. I spent the last 2 weeks trying to craft a solution... It feels like I don't understand one thing to make this work. Any advice is appreciated.
Table setup
FUNCCODE | POSCODE | DEVCODE
11 1 NULL
12 NULL 1
13 2 NULL
14 NULL 2
The table needs to be rearranged and then inserted into a separate table called JOINT which is setup as:
POSCODE | POSFUNCCODE |DEVCODE | DEVFUNCCODE
1 11 1 12
2 13 2 14
Some of my attempts XD
Each join creates only 2 of the columns I need
SELECT
dbo.POSITION.POSCODE AS POSCODE,
dbo.FUNC.FUNCCODE AS POSFUNCCODE
FROM FUNC
INNER JOIN POSITION ON dbo.POSITION.POSCODE = dbo.FUNC.POSCODE
UNION ALL
SELECT
dbo.DEVICE.DEVCODE AS DEVCODE,
dbo.FUNC.FUNCCODE AS DEVFUNCCODE
FROM FUNC
INNER JOIN DEVICE ON dbo.DEVICE.DEVCODE = dbo.FUNC.DEVCODE
ORDER BY 1;
Only inserts the last row values
DECLARE #DATE DATETIME = GETDATE()
DECLARE #PC INT;
SELECT #PC = POSCODE
FROM func
WHERE poscode != 0
ORDER BY 1;
DECLARE #FCP INT;
SELECT #FCP = FUNCCODE
FROM FUNC
WHERE POSCODE != 0
ORDER BY 1;
DECLARE #DC INT;
SELECT #DC = devcode
FROM func
WHERE devcode != 0
ORDER BY 1;
DECLARE #FCD INT
SELECT #FCD = FUNCCODE
FROM FUNC
WHERE DEVCODE != 0
ORDER BY 1
INSERT INTO JOINT (POSCODE, POSFUNCCODE, DEVCODE, DEVFUNCCODE, JOINTTIME,
JOINTSTATUS)
VALUES (#PC, #FCP, #DC, #FCD, #DATE, 1)
If my understanding of your problem is correct, I think the below query would be a solution.
INSERT INTO JOINT (POSTCODE, DEVCODE, POSFUNCCODE, DEVFUNCCODE)
SELECT
POSTCODE,
DEVCODE,
MAX(CASE
WHEN POSCODE IS NOT NULL THEN FUNCCODE
ELSE NULL
END) POSFUNCCODE,
MAX(CASE
WHEN DEVCODE IS NOT NULL THEN FUNCCODE
ELSE NULL
END) DEVFUNCCODE
FROM FUNC
GROUP BY POSTCODE,DEVCODE
Second version after a better understanding
INSERT INTO JOINT (POSTCODE, DEVCODE, POSFUNCCODE, DEVFUNCCODE)
SELECT
t1.POSTCODE,
t2.DEVCODE,
t1.POSFUNCCODE,
t2.DEVFUNCCODE
(SELECT
POSTCODE,
MAX(CASE
WHEN POSCODE IS NOT NULL THEN FUNCCODE
ELSE NULL
END) POSFUNCCODE
FROM FUNC
GROUP BY POSTCODE) t1
INNER JOIN
(SELECT
DEVCODE,
MAX(CASE
WHEN DEVCODE IS NOT NULL THEN FUNCCODE
ELSE NULL
END) DEVFUNCCODE
FROM FUNC
GROUP BY DEVCODE) t2
ON t1.POSTCODE = t2.DEVCODE
Against my better judgment, I created a loop which inserted the proper values.... I know this is not the correct way to approach this, please excuse me since my experience in SQL is very little. But this corrects the interface issue in the client program. Shout out to #user4219031 for guidance!
DECLARE #DATE DATETIME = GETDATE()
DECLARE #PC INT = 0;
DECLARE #FCP INT = 12;
DECLARE #DC INT = 0;
DECLARE #FCD INT = 13
WHILE ( #PC < 739 )
BEGIN
INSERT INTO JOINT (POSCODE, POSFUNCCODE, DEVCODE, DEVFUNCCODE, JOINTTIME, JOINTSTATUS)
VALUES( #PC, #FCP, #DC, #FCD, #DATE, 1)
SET #PC = #PC + 1
SET #FCP = #FCP +2
SET #DC = #DC + 1
SET #FCD = #FCD + 2
END
EDIT: I changed my query to account for NULL POSCODE or DEVCODE.
SQL Fiddle
MS SQL Server 2017 Schema Setup:
CREATE TABLE t ( FUNCCODE int, POSCODE int, DEVCODE int ) ;
INSERT INTO t (FUNCCODE, POSCODE, DEVCODE)
VALUES
( 11, 1, NULL )
, ( 12, NULL, 1 )
, ( 13, 2, NULL )
, ( 14, NULL, 2 )
, ( 42, NULL, 1 )
, ( 77, NULL, 7 )
, ( 88, NULL, 8 )
, ( 99, 9, NULL )
;
Create New Table And Insert Records
CREATE TABLE ti ( POSCODE int, pos_FUNCCODE int, DEVCODE int, dev_FUNCCODE int ) ;
INSERT INTO ti ( POSCODE, pos_FUNCCODE, DEVCODE, dev_FUNCCODE)
SELECT t1.POSCODE
, t1.FUNCCODE AS pos_FUNCODE
, t2.DEVCODE
, t2.FUNCCODE AS dev_FUNCCODE
FROM t t1
FULL OUTER JOIN t t2 ON t1.POSCODE = t2.DEVCODE
WHERE t1.POSCODE IS NOT NULL OR t2.DEVCODE IS NOT NULL
;
What's In The New Table?:
SELECT * FROM ti
Results:
| POSCODE | pos_FUNCCODE | DEVCODE | dev_FUNCCODE |
|---------|--------------|---------|--------------|
| 1 | 11 | 1 | 12 |
| 1 | 11 | 1 | 42 |
| 2 | 13 | 2 | 14 |
| 9 | 99 | (null) | (null) |
| (null) | (null) | 7 | 77 |
| (null) | (null) | 8 | 88 |
==========ORIGINAL==========
SQL Fiddle
MS SQL Server 2017 Schema Setup:
CREATE TABLE t ( FUNCCODE int, POSCODE int, DEVCODE int ) ;
INSERT INTO t (FUNCCODE, POSCODE, DEVCODE)
VALUES
( 11, 1, NULL )
, ( 12, NULL, 1 )
, ( 13, 2, NULL )
, ( 14, NULL, 2 )
;
Create New Table And Insert Records
CREATE TABLE ti ( POSCODE int, pos_FUNCCODE int, DEVCODE int, dev_FUNCCODE int ) ;
INSERT INTO ti ( POSCODE, pos_FUNCCODE, DEVCODE, dev_FUNCCODE)
SELECT t1.POSCODE
, t1.FUNCCODE AS pos_FUNCODE
, t2.DEVCODE
, t2.FUNCCODE AS dev_FUNCCODE
FROM t t1
INNER JOIN t t2 ON t1.POSCODE = t2.DEVCODE
WHERE t1.POSCODE IS NOT NULL
;
What's In The New Table?:
SELECT * FROM ti
Results:
| POSCODE | pos_FUNCCODE | DEVCODE | dev_FUNCCODE |
|---------|--------------|---------|--------------|
| 1 | 11 | 1 | 12 |
| 2 | 13 | 2 | 14 |

Convert Rows into Columns in Sql query to column Time

I have a problem to ask:
Time Pass Fail
-------------------------
08:30 10 2
09:30 12 1
10:30 20 0
11:30 30 40
I am trying to convert rows into column and display such information in below
08:30 09:30 10:30 11:30
------------------------------
10 12 20 30
2 1 0 40
Please help me!
Thank you!
This should do the trick...
IF OBJECT_ID('tempdb..#TestData', 'U') IS NOT NULL
DROP TABLE #TestData;
CREATE TABLE #TestData (
[Time] DATETIME NOT NULL,
Pass INT NOT NULL,
Fail INT NOT null
);
INSERT #TestData (Time, Pass, Fail) VALUES
('08:30',10, 2),
('09:30',12, 1),
('10:30',20, 0),
('11:30',30, 40);
SELECT
[P/F] = CASE WHEN pf.id = 1 THEN 'Pass' ELSE 'Fail' END,
[08:30] = MAX(CASE WHEN td.[Time] = '08:30' THEN pf.Value END),
[09:30] = MAX(CASE WHEN td.[Time] = '09:30' THEN pf.Value END),
[10:30] = MAX(CASE WHEN td.[Time] = '10:30' THEN pf.Value END),
[11:30] = MAX(CASE WHEN td.[Time] = '11:30' THEN pf.Value END)
FROM
#TestData td
CROSS APPLY ( VALUES (1, td.Pass), (2, td.Fail) ) pf (id, Value)
GROUP BY
pf.id;
Results...
P/F 08:30 09:30 10:30 11:30
---- ----------- ----------- ----------- -----------
Pass 10 12 20 30
Fail 2 1 0 40

SELECT CASE vs. CASE IN SQL

I do not quite understand why those two different codesamples return a different value.
somehow incorrect but working syntax, returns false results, e.g it returns 0 when the comparison is done over two equal values:
(SELECT CASE
WHEN
SUM(V.IsCompatible) OVER
(PARTITION BY ComputerName, UserID) = ApplicationCount
THEN 1 ELSE 0 END
) AS CompatibleUser
The one below returns the correct values, ie. 1 when there are two equal values compared.
(CASE
WHEN
SUM(V.IsCompatible) OVER
(PARTITION BY ComputerName, UserID) = ApplicationCount
THEN 1 ELSE 0 END
) AS CompatibleUser
or even simpler:
(SELECT CASE
WHEN
X = Y
THEN 1 ELSE 0 END
) AS Result
X = 22 AND Y = 22 => Result = 0
(CASE
WHEN
X = Y
THEN 1 ELSE 0 END
) AS Result
X = 22 AND Y = 22 => Result = 1
I understand applying the correct syntax is important, and I am aware of the SELECT CASE syntax in T-SQL, but I do not understand how the first code sample is evaluated and delivering an unexpected result.
update: full query in it's context
select userapplication.username,
computerdetails.computername,
sum(userapplication.iscompatible)
over (partition by computerdetails.computername,
userapplication.userid) as compatiblecount,
userapplication.applicationcount,
( case
when sum(userapplication.iscompatible)
over (partition by
computerdetails.computername,
userapplication.userid) <> userapplication.applicationcount
then 0
else 1
end
) as usercomputeriscompatible
from computerdetails
right outer join usercomputer
on computerdetails.computerid = usercomputer.computerid
right outer join userapplication
on usercomputer.gebruikerid = userapplication.userid
so userComputerIsCompatible is the result in question here
I think the reason for this behavior is the next one: the expressions like (SELECT ...) are considered to be sub-queries even they don't have FROM clause. Is assume the source of data for these (false) "sub-queries" is only the current row. So, (SELECT expression) is interpreted as (SELECT expression FROM current_row) and (SELECT SUM(iscompatible)OVER(...)) is executed as (SELECT SUM(iscompatible)OVER(current_row)).
Argument: analyzing execution plan for (SELECT SUM(IsWeb) OVER(PARTITION BY OrderDate) [FROM current_row]) expression
I see a Constant Scan (Scan an internal table of constants) operator instead of Clustered Index Scan before Segment and Stream Aggregate ([Expr1007] = Scalar Operator(SUM(#OrderHeader.[IsWeb] as [h].[IsWeb]))) operators. This internal table (Constant Scan) is constructed from current row.
Example (tested with SQL2005SP3 and SQL2008):
DECLARE #OrderHeader TABLE
(
OrderHeaderID INT IDENTITY PRIMARY KEY
,OrderDate DATETIME NOT NULL
,IsWeb TINYINT NOT NULL --or BIT
);
INSERT #OrderHeader
SELECT '20110101', 0
UNION ALL
SELECT '20110101', 1
UNION ALL
SELECT '20110101', 1
UNION ALL
SELECT '20110102', 1
UNION ALL
SELECT '20110103', 0
UNION ALL
SELECT '20110103', 0;
SELECT *
,SUM(IsWeb) OVER(PARTITION BY OrderDate) SumExpression_1
FROM #OrderHeader h
ORDER BY h.OrderDate;
SELECT *
,(SELECT SUM(IsWeb) OVER(PARTITION BY OrderDate)) SumWithSubquery_2
FROM #OrderHeader h
ORDER BY h.OrderDate;
Results:
OrderHeaderID OrderDate IsWeb SumExpression_1
------------- ----------------------- ----- ---------------
1 2011-01-01 00:00:00.000 0 2
2 2011-01-01 00:00:00.000 1 2
3 2011-01-01 00:00:00.000 1 2
4 2011-01-02 00:00:00.000 1 1
5 2011-01-03 00:00:00.000 0 0
6 2011-01-03 00:00:00.000 0 0
OrderHeaderID OrderDate IsWeb SumWithSubquery_2
------------- ----------------------- ----- -----------------
1 2011-01-01 00:00:00.000 0 0
2 2011-01-01 00:00:00.000 1 1
3 2011-01-01 00:00:00.000 1 1
4 2011-01-02 00:00:00.000 1 1
5 2011-01-03 00:00:00.000 0 0
6 2011-01-03 00:00:00.000 0 0
I tried your code and I get the same results for both queries. Here's the code I tried:
DECLARE #X INT = 22
DECLARE #Y INT = 22
SELECT (SELECT CASE
WHEN
#X = #Y
THEN 1 ELSE 0 END
) AS Result
SELECT (CASE
WHEN
#X = #Y
THEN 1 ELSE 0 END
) AS Result
Result is 1 and 1
I ran this on SQL Server 2008 R2

Resources