Is there a better way to generate [0 ... 9999] than this:
SELECT
(a3.id + a2.id + a1.id + a0.id) id
FROM
(
SELECT 0 id UNION ALL
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7 UNION ALL
SELECT 8 UNION ALL
SELECT 9
) a0
CROSS JOIN
(
SELECT 0 id UNION ALL
SELECT 10 UNION ALL
SELECT 20 UNION ALL
SELECT 30 UNION ALL
SELECT 40 UNION ALL
SELECT 50 UNION ALL
SELECT 60 UNION ALL
SELECT 70 UNION ALL
SELECT 80 UNION ALL
SELECT 90
) a1
CROSS JOIN
(
SELECT 0 id UNION ALL
SELECT 100 UNION ALL
SELECT 200 UNION ALL
SELECT 300 UNION ALL
SELECT 400 UNION ALL
SELECT 500 UNION ALL
SELECT 600 UNION ALL
SELECT 700 UNION ALL
SELECT 800 UNION ALL
SELECT 900
) a2
CROSS JOIN
(
SELECT 0 id UNION ALL
SELECT 1000 UNION ALL
SELECT 2000 UNION ALL
SELECT 3000 UNION ALL
SELECT 4000 UNION ALL
SELECT 5000 UNION ALL
SELECT 6000 UNION ALL
SELECT 7000 UNION ALL
SELECT 8000 UNION ALL
SELECT 9000
) a3
ORDER BY id
Any feedback appreciated.
You could write it like this:
;WITH x as
(
SELECT 0 id UNION ALL
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7 UNION ALL
SELECT 8 UNION ALL
SELECT 9
)
SELECT
row_number() over (order by (select 1))-1 id
FROM x a0
CROSS JOIN x a1
CROSS JOIN x a2
CROSS JOIN x a3
By removing the order by you gained a little.
I am not sure why this answer was removed from POST, this also produced desired output
;WITH x as
(
select id from
(values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) x(id)
)
SELECT
(a3.id * 1000 +
a2.id * 100 + a1.id * 10 + a0.id) id
FROM x a2
CROSS JOIN x a0
CROSS JOIN x a1
CROSS JOIN x a3
WITH a AS (
SELECT 0 AS a1
UNION ALL
SELECT a1+1 FROM a WHERE a1+1<10000
)
SELECT * FROM a
OPTION (Maxrecursion 10000)
Related
I am trying to run below query and getting the error.
ERROR: This type of correlated subquery pattern is not supported due to internal error. How can I re write subquery without altering the result. Highlighted in bold is causing the issue.
SELECT
bin_max,
bin_count,
ROUND(RATIO_TO_REPORT(bin_count) over (), 5) bin_percent
FROM
(
SELECT
bin_max,
cum_count - lag(cum_count, 1) over (ORDER BY bin_max) bin_count
FROM
(
SELECT
b.bin_max,
(select COUNT(*)
FROM ndw_owner.MBP_USER_LOGINS_BY_USER ulbu
WHERE
ulbu.DAYS_SINCE_FIRST_LOGIN > 30
and ulbu.PROJECTED_30_DAY_LOGINS <= b.bin_max
) cum_count
FROM
(SELECT * FROM ( SELECT 1 AS BIN_MAX
UNION
SELECT 2 AS BIN_MAX UNION
SELECT 3 AS BIN_MAX UNION
SELECT 4 AS BIN_MAX UNION
SELECT 5 AS BIN_MAX UNION
SELECT 10 AS BIN_MAX UNION
SELECT 15 AS BIN_MAX UNION
SELECT 20 AS BIN_MAX UNION
SELECT 30 AS BIN_MAX UNION
SELECT 40 AS BIN_MAX UNION
SELECT 60 AS BIN_MAX UNION
SELECT 80 AS BIN_MAX UNION
SELECT 99999999 AS BIN_MAX
)
) b
)
);
Change the sub query to perform an inequality join between b and ulbu. This will make the data you need in the top query.
I am stuck at this T-SQL query.
I have table below
Age SectioName Cost
---------------------
1 Section1 100
2 Section1 200
1 Section2 500
3 Section2 100
4 Section2 200
Lets say for each section I can have maximum 5 Age. In above table there are some missing Ages. How do I insert missing Ages for each section. (Possibly without using cursor). The cost would be zero for missing Ages
So after the insertion the table should look like
Age SectioName Cost
---------------------
1 Section1 100
2 Section1 200
3 Section1 0
4 Section1 0
5 Section1 0
1 Section2 500
2 Section2 0
3 Section2 100
4 Section2 200
5 Section2 0
EDIT1
I should have been more clear with my question. The maximum age is dynamic value. It could be 5,6,10 or someother value but it will be always less than 25.
I think I got it
;WITH tally AS
(
SELECT 1 AS r
UNION ALL
SELECT r + 1 AS r
FROM tally
WHERE r < 5 -- this value could be dynamic now
)
select n.r, t.SectionName, 0 as Cost
from (select distinct SectionName from TempFormsSectionValues) t
cross join
(select ta.r FROM tally ta) n
where not exists
(select * from TempFormsSectionValues where YearsAgo = n.r and SectionName = t.SectionName)
order by t.SectionName, n.r
You can use this query to select missing value:
select n.num, t.SectioName, 0 as Cost
from (select distinct SectioName from table1) t
cross join
(select 1 as num union select 2 union select 3 union select 4 union select 5) n
where not exists
(select * from table1 where table1.age = n.num and table1.SectioName = t.SectioName)
It creates a Cartesian product of sections and numbers 1 to 5 and then selects those that doesn't exist yet. You can then use this query for the source of insert into your table.
SQL Fiddle (it has order by added to check the results easier but it's not necessary for inserting).
Use below query to generate missing rows
SELECT t1.Age,t1.Section,ISNULL(t2.Cost,0) as Cost
FROM
(
SELECT 1 as Age,'Section1' as Section,0 as Cost
UNION
SELECT 2,'Section1',0
UNION
SELECT 3,'Section1',0
UNION
SELECT 4,'Section1',0
UNION
SELECT 5,'Section1',0
UNION
SELECT 1,'Section2',0
UNION
SELECT 2,'Section2',0
UNION
SELECT 3,'Section2',0
UNION
SELECT 4,'Section2',0
UNION
SELECT 5,'Section2',0
) as t1
LEFT JOIN test t2
ON t1.Age=t2.Age AND t1.Section=t2.Section
ORDER BY Section,Age
SQL Fiddle
You can utilize above result set for inserting missing rows by using EXCEPT operator to exclude already existing rows in table -
INSERT INTO test
SELECT t1.Age,t1.Section,ISNULL(t2.Cost,0) as Cost
FROM
(
SELECT 1 as Age,'Section1' as Section,0 as Cost
UNION
SELECT 2,'Section1',0
UNION
SELECT 3,'Section1',0
UNION
SELECT 4,'Section1',0
UNION
SELECT 5,'Section1',0
UNION
SELECT 1,'Section2',0
UNION
SELECT 2,'Section2',0
UNION
SELECT 3,'Section2',0
UNION
SELECT 4,'Section2',0
UNION
SELECT 5,'Section2',0
) as t1
LEFT JOIN test t2
ON t1.Age=t2.Age AND t1.Section=t2.Section
EXCEPT
SELECT Age,Section,Cost
FROM test
SELECT * FROM test
ORDER BY Section,Age
http://www.sqlfiddle.com/#!3/d9035/11
I have the following table:
parent_id child_id child_class
1 2 1
1 3 1
1 4 2
2 5 2
2 6 2
Parent_id represents a folder id. Child id represents either a child folder (where child_class=1) or child file (where child_class=2).
I'd like to get a rollup counter (bottom up) of all files only (child_class=2) the following way. for example if C is a leaf folder (no child folders) with 5 files, and B is a parent folder of C that has 4 files in it, the counter on C should say 5 and the counter on B should say 9 (=5 from C plus 4 files in B) and so forth recursively going bottom up taking into consideration sibling folders etc.
In the example above I expect the results below (notice 3 is a child folder with no files in it):
parent_id FilesCounter
3 0
2 2
1 3
I prefer an SQL query for performance but function is also possible.
I tried mixing hirarchical query with rollup (sql 2008 r2) with no success so far.
Please advise.
This CTE should do the trick... Here is the SQLFiddle.
SELECT parent_id, child_id, child_class,
(SELECT COUNT(*) FROM tbl a WHERE a.parent_id = e.parent_id AND child_class <> 1) AS child_count
INTO tbl2
FROM tbl e
;WITH CTE (parent_id, child_id, child_class, child_count)
AS
(
-- Start with leaf nodes
SELECT parent_id, child_id, child_class, child_count
FROM tbl2
WHERE child_id NOT IN (SELECT parent_id from tbl)
UNION ALL
-- Recursively go up the chain
SELECT e.parent_id, e.child_id, e.child_class, e.child_count + d.child_count
FROM tbl2 e
INNER JOIN CTE AS d
ON e.child_id = d.parent_id
)
-- Statement that executes the CTE
SELECT FOLDERS.parent_id, max(ISNULL(child_count,0)) FilesCounter
FROM (SELECT parent_id FROM tbl2 WHERE parent_id NOT IN (select child_id from tbl2)
UNION
SELECT child_id FROM tbl2 WHERE child_class = 1) FOLDERS
LEFT JOIN CTE ON FOLDERS.parent_id = CTE.parent_id
GROUP BY FOLDERS.parent_id
Zak's answer was close, but the root folder did not rollup well. The following does the work:
with par_child as (
select 1 as parent_id, 2 as child_id, 1 as child_class
union all select 1, 3, 1
union all select 1, 4, 2
union all select 2, 5, 1
union all select 2, 6, 2
union all select 2, 10, 2
union all select 3, 11, 2
union all select 3, 7 , 2
union all select 5, 8 , 2
union all select 5, 9 , 2
union all select 5, 12, 1
union all select 5, 13, 1
)
, child_cnt as
(
select parent_id as root_parent_id, parent_id, child_id, child_class, 1 as lvl from par_child union all
select cc.root_parent_id, pc.parent_id, pc.child_id, pc.child_class, cc.lvl + 1 as lvl from
par_child pc join child_cnt cc on (pc.parent_id=cc.child_id)
),
distinct_folders as (
select distinct child_id as folder_id from par_child where child_class=1
)
select root_parent_id, count(child_id) as cnt from child_cnt where child_class=2 group by root_parent_id
union all
select folder_id, 0 from distinct_folders df where not exists (select 1 from par_child pc where df.folder_id=pc.parent_id)
I have this script:
SELECT 'pro' as descript, COUNT(*) as cnt FROM Trade.TradesMen where TradesManAccountType_Value = 2 AND HasTradeListing = 1
UNION ALL
SELECT 'std' as descript, COUNT(*) as cnt FROM Trade.TradesMen tm
INNER JOIN Membership.Members m ON m.MemberId = tm.MemberId
INNER JOIN aspnet_Membership am ON am.UserId = m.AspNetUserId
WHERE tm.TradesManAccountType_Value = 1 AND tm.HasTradeListing = 1 AND am.IsApproved = 1
UNION ALL
SELECT 'listed' as descript, COUNT(*) as cnt FROM Trade.TradesMen where HasTradeListing = 1
UNION ALL
SELECT 'all' as descript, COUNT(*) as cnt FROM Trade.TradesMen
insert into Admin.VersionHistory values(4,cnt,CURRENT_TIMESTAMP) //is NOT correct
this produces:
1 pro 32549
2 std 13096
3 listed 230547
4 all 231638
I want to add the above as rows in my table: Admin.VersionHistory which has columns VersionHistory type int auto-increment and is the ID, Version which is of type varchar(50) and a datatime stamp
thanks
(updated with new info from OP)
From the top of my head, it would look something like this.
INSERT INTO Admin.VersionHistory (Version, NumberOf, DateAndTime)
SELECT descript, CAST(cnt AS VARCHAR), SYSDATE
FROM
(
SELECT 'pro' as descript, COUNT(*) as cnt FROM Trade.TradesMen where TradesManAccountType_Value = 2 AND HasTradeListing = 1
UNION ALL
SELECT 'std' as descript, COUNT(*) as cnt FROM Trade.TradesMen tm
INNER JOIN Membership.Members m ON m.MemberId = tm.MemberId
INNER JOIN aspnet_Membership am ON am.UserId = m.AspNetUserId
WHERE tm.TradesManAccountType_Value = 1 AND tm.HasTradeListing = 1 AND am.IsApproved = 1
UNION ALL
SELECT 'listed' as descript, COUNT(*) as cnt FROM Trade.TradesMen where HasTradeListing = 1
UNION ALL
SELECT 'all' as descript, COUNT(*) as cnt FROM Trade.TradesMen
) ;
This is assuming the VersionHistoryIdcolumn is automatically seeded by the database. With each insert, an ID number will be automatically inserted.
Not sure what you want to achieve with the CURRENT_TIMESTAMP column though. I put SYSDATE as a timestamp.
The NumberOf column contains the count data. Name it as you see fit.
insert into Admin.VersionHistory
SELECT 'all', COUNT(*),current_timestamp FROM Trade.TradesMen
Can someone help me with this query?
SELECT p.OwnerName, SUM(ru.MonthlyRent) AS PotentinalRent, SUM(
(SELECT COUNT(t.ID) * ru.MonthlyRent FROM tblTenant t
WHERE t.UnitID = ru.ID)
) AS ExpectedRent
FROM tblRentalUnit ru
LEFT JOIN tblProperty p ON p.ID = ru.PropertyID
GROUP BY p.OwnerName
I'm having problems with the second sum, it won't let me do it. Evidently SUM won't work on subqueries, but I need to calculate the expected rent (MonthlyRent if there is a tenant assigned to the RentalUnit's id, 0 of they're not). How can I make this work?
SELECT p.OwnerName, SUM(ru.MonthlyRent) AS PotentialRent, SUM(cnt) AS ExpectedRent
FROM tblRentalUnit ru
LEFT JOIN
tblProperty p
ON p.ID = ru.PropertyID
OUTER APPLY
(
SELECT COUNT(t.id) * ru.MonthlyRent AS cnt
FROM tblTenant t
WHERE t.UnitID = ru.ID
) td
GROUP BY p.OwnerName
Here's a test script to check:
WITH tblRentalUnit AS
(
SELECT 1 AS id, 100 AS MonthlyRent, 1 AS PropertyID
UNION ALL
SELECT 2 AS id, 300 AS MonthlyRent, 2 AS PropertyID
),
tblProperty AS
(
SELECT 1 AS id, 'Owner 1' AS OwnerName
UNION ALL
SELECT 2 AS id, 'Owner 2' AS OwnerName
),
tblTenant AS
(
SELECT 1 AS id, 1 AS UnitID
UNION ALL
SELECT 2 AS id, 1 AS UnitID
)
SELECT p.OwnerName, SUM(ru.MonthlyRent) AS PotentialRent, SUM(cnt) AS ExpectedRent
FROM tblRentalUnit ru
LEFT JOIN
tblProperty p
ON p.ID = ru.PropertyID
OUTER APPLY
(
SELECT COUNT(t.id) * ru.MonthlyRent AS cnt
FROM tblTenant t
WHERE t.UnitID = ru.ID
) td
GROUP BY p.OwnerName
What is the meaning of the sum of the unitMonthlyRent times the number of tenants, for some partiicular rental unit (COUNT(t.ID) * ru.MonthlyRent )?
Is it the case that all you are trying to do is see the difference between the total potential rent from all untis versus the expected rent (From only occcupied units) ? If so, then try this
Select p.OwnerName,
Sum(r.MonthlyRent) AS PotentinalRent,
Sum(Case t.Id When Null Then 0
Else r.MonthlyRent End) ExpectedRent
From tblRentalUnit r
Left Join tblTenant t
On t.UnitID = r.ID
left Join tblProperty p
On p.ID = r.PropertyID)
Group By p.OwnerName