Repository navigation
Expand file tree
/
Copy pathSample Query StackOverflow.sql
More file actions
89 lines (74 loc) · 2.05 KB
/
Copy pathSample Query StackOverflow.sql
File metadata and controls
89 lines (74 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
SET STATISTICS IO, TIME ON;
SELECT p.Id,
p.AcceptedAnswerId,
p.AnswerCount,
p.ClosedDate,
p.CommentCount,
p.CommunityOwnedDate,
p.CreationDate,
p.FavoriteCount,
p.LastActivityDate,
p.LastEditDate,
p.LastEditorDisplayName,
p.LastEditorUserId,
p.OwnerUserId,
p.ParentId,
p.PostTypeId,
ptype.Type,
p.Score,
p.Tags,
p.title,
p.ViewCount,
pt.Tag
FROM Posts p
JOIN PostTags pt ON pt.PostId = p.Id
JOIN PostTypes ptype ON p.PostTypeId = ptype.Id
JOIN Users u ON p.OwnerUserId = u.Id
JOIN Comments c ON p.Id = c.PostId
WHERE p.CreationDate > '2013-01-01'
;
GO
SELECT *
FROM Posts p
JOIN Users u on p.OwnerUserId = u.Id
JOIN Votes v ON p.Id = v.PostId
WHERE u.DisplayName = 'Jon Skeet'
;
GO
SELECT Id, scores
FROM Posts
;
GO
SET STATISTICS IO, TIME ON;
-- Create a temp table with some data
IF OBJECT_ID('tempdb..#Orders') IS NOT NULL DROP TABLE #Orders;
CREATE TABLE #Orders (
OrderID INT IDENTITY(1,1) PRIMARY KEY,
CustomerID INT NOT NULL,
OrderDate DATETIME2 NOT NULL,
Amount DECIMAL(18,2) NOT NULL,
Notes NVARCHAR(400) NULL
);
-- Populate ~50k rows so IO is non-trivial
INSERT INTO #Orders (CustomerID, OrderDate, Amount, Notes)
SELECT TOP (50000)
ABS(CHECKSUM(NEWID())) % 1000,
DATEADD(MINUTE, -1 * (ROW_NUMBER() OVER (ORDER BY (SELECT NULL))), SYSDATETIME()),
CAST((ABS(CHECKSUM(NEWID())) % 100000) / 100.0 AS DECIMAL(18,2)),
REPLICATE(N'x', 200)
FROM sys.all_objects a CROSS JOIN sys.all_objects b;
GO
-- Query 1: clustered index scan with aggregation
SELECT CustomerID, COUNT(*) AS Orders, SUM(Amount) AS Total
FROM #Orders
GROUP BY CustomerID
ORDER BY Total DESC;
-- Query 2: filter + sort, joins to a system view to add a second table to the IO output
SELECT TOP (100) o.OrderID, o.CustomerID, o.Amount, o.OrderDate, t.name AS TypeName
FROM #Orders AS o
CROSS JOIN sys.types AS t
WHERE o.Amount > 500
ORDER BY o.OrderDate DESC;
GO
DROP TABLE #Orders;
GO