SQL Subquery all data from same table - sql

I have a table where I would like to have one field (account) always shown then subqueries for counts or sums with criteria.
Example:
select ndhist_acct_nbr,
(select count(ndhist_acct_nbr) from dbo.nd_history where ndhist_type = '30'
and ndhist_rsn = '0' and ndhist_trcd = 'NF*' and ndhist_ref_type = '0' and ndhist_dt >= '03/01/2013') as NSF_TOTAL,
(select sum(ndhist_amt) from dbo.nd_history where ndhist_type = '30'
and ndhist_rsn = '98' and ndhist_trcd = 'TW0' and ndhist_ref_type = '11' and ndhist_dt >= '03/01/2013') as SIG_SPEND,
(select count(ndhist_acct_nbr) from dbo.nd_history where ndhist_type = '30'
and ndhist_rsn = '23' and ndhist_trcd = 'TW0' and ndhist_ref_type = '11' and ndhist_dt >= '03/01/2013') as PIN_TRANS,
(select count(ndhist_acct_nbr) from dbo.nd_history where ndhist_type = '30'
and ndhist_rsn = '21' and ndhist_trcd = 'SC*' and ndhist_ref_type = '0' and ndhist_dt >= '03/01/2013') as FOREIGN_AMT_FEE
from dbo.nd_history
group by ndhist_acct_nbr
The problem is the results - all of the account numbers show up but the counts/sum fields all repeat the data. Any help would be awesome!

Your subqueries are standalone - they don't depend on ndhist_acct_nbr field in any way, so the result is always the same.
Besides, this technique (using this many subqueries for every row of output) is a bad idea.
You should simplify the query, and instead of count distinct and subqueries, make sum(case when ... clauses.

Try:
select ndhist_acct_nbr,
count(case when ndhist_type = '30' and ndhist_rsn = '0' and ndhist_trcd = 'NF*' and ndhist_ref_type = '0' and ndhist_dt >= '03/01/2013'
then ndhist_acct_nbr end) as NSF_TOTAL,
sum(case when ndhist_type = '30' and ndhist_rsn = '98' and ndhist_trcd = 'TW0' and ndhist_ref_type = '11' and ndhist_dt >= '03/01/2013'
then ndhist_amt end) as SIG_SPEND,
count(case when ndhist_type = '30' and ndhist_rsn = '23' and ndhist_trcd = 'TW0' and ndhist_ref_type = '11' and ndhist_dt >= '03/01/2013'
then ndhist_acct_nbr end) as PIN_TRANS,
count(case when ndhist_type = '30' and ndhist_rsn = '21' and ndhist_trcd = 'SC*' and ndhist_ref_type = '0' and ndhist_dt >= '03/01/2013'
then ndhist_acct_nbr end) as FOREIGN_AMT_FEE
from dbo.nd_history
group by ndhist_acct_nbr
You can use derived columns from the results by putting the whole query inside an inline query and then selecting from it - like so:
select sq.*,
NSF_TOTAL*5 + SIG_SPEND*0.10 + PIN_TRANS*0.05 + FOREIGN_ATM_FEE as TOTAL_INCOME
from
(select ndhist_acct_nbr,
count(case when ndhist_type = '30' and ndhist_rsn = '0' and ndhist_trcd = 'NF*' and ndhist_ref_type = '0' and ndhist_dt >= '03/01/2013'
then ndhist_acct_nbr end) as NSF_TOTAL,
sum(case when ndhist_type = '30' and ndhist_rsn = '98' and ndhist_trcd = 'TW0' and ndhist_ref_type = '11' and ndhist_dt >= '03/01/2013'
then ndhist_amt end) as SIG_SPEND,
count(case when ndhist_type = '30' and ndhist_rsn = '23' and ndhist_trcd = 'TW0' and ndhist_ref_type = '11' and ndhist_dt >= '03/01/2013'
then ndhist_acct_nbr end) as PIN_TRANS,
count(case when ndhist_type = '30' and ndhist_rsn = '21' and ndhist_trcd = 'SC*' and ndhist_ref_type = '0' and ndhist_dt >= '03/01/2013'
then ndhist_acct_nbr end) as FOREIGN_AMT_FEE
from dbo.nd_history
group by ndhist_acct_nbr) sq
This could be done more elegantly via a CTE if you are using a RDBMS (such as Oracle, PostgreSQL or SQLServer) that supports CTEs.

Related

SUM 3 different "CASE" columns with three different totals

I'm new to this so I'm sorry if I asked this question wrong. But I'm trying to get 4 different SUM's from my table that uses 4 different cases. But I want the id to be listed only once with the totals. I'll show you what I have, and what I'm trying to get. Please help if possible.
SELECT schools.name, articles.competition_place,
Case when articles.competition = 'yes' and competition_place = '1' then int '100'
when articles.competition = 'yes' and competition_place = '2' then int '60'
when articles.competition = 'yes' and competition_place = '3' then int '20'
ELSE 0 end AS "Competition_Score",
Case when articles.out_reach = 'yes' then int '30'
ELSE 0 end AS "out_reach_Score",
CASE when schools.school_id is not null then int '5'
ELSE 0 end as "article_score",
(Case when articles.competition = 'yes' and competition_place = '1' then int '100'
when articles.competition = 'yes' and competition_place = '2' then int '60'
when articles.competition = 'yes' and competition_place = '3' then int '20'
ELSE 0 end) +
(Case when articles.out_reach = 'yes' then int '30'
ELSE 0 end) +
(CASE when schools.school_id is not null then int '5'
ELSE 0 end) as "total_score"
from articles
join clubs on articles.club_id = clubs.club_id
join schools on clubs.school_id = schools.school_id
My table that I have
And this is what I'm trying to get.
This is the table I'm trying to get
Is this possible?
use aggregation and group by
SELECT schools.name, articles.competition_place,
sum(Case when articles.competition = 'yes' and competition_place = '1' then int '100'
when articles.competition = 'yes' and competition_place = '2' then int '60'
when articles.competition = 'yes' and competition_place = '3' then int '20'
ELSE 0 end) AS "Competition_Score",
sum(Case when articles.out_reach = 'yes' then int '30'
ELSE 0 end) AS "out_reach_Score",
sum(CASE when schools.school_id is not null then int '5'
ELSE 0 end) as "article_score",
sum((Case when articles.competition = 'yes' and competition_place = '1' then int '100'
when articles.competition = 'yes' and competition_place = '2' then int '60'
when articles.competition = 'yes' and competition_place = '3' then int '20'
ELSE 0 end)) +
sum((Case when articles.out_reach = 'yes' then int '30'
ELSE 0 end)) +
sum(CASE when schools.school_id is not null then int '5'
ELSE 0 end)) as "total_score"
from articles
join clubs on articles.club_id = clubs.club_id
join schools on clubs.school_id = schools.school_id
group by schools.name, articles.competition_place

How to add Average along with sum

My query is :
select
TIERING_2, ASP_NAME ,
sum(case when SUBCASE_MEASURED = '1' AND FE_TYPE = 'ASP' AND CLOSE_MONTH = '3' and region = 'EEMEA' AND SCHEDULED_RESCHEDULED = 'Scheduled' then 1 else 0 end) DA_SCHEDULED,
sum(case when SUBCASE_MEASURED = '1' AND FE_TYPE = 'ASP' AND CLOSE_MONTH = '3' and region = 'EEMEA' AND SCHEDULED_RESCHEDULED = 'Reactive' then 1 else 0 end) FE_DELAY,
sum(case when SUBCASE_MEASURED = '1' AND FE_TYPE = 'ASP' AND CLOSE_MONTH = '3' and region = 'EEMEA' AND SCHEDULED_RESCHEDULED = 'Reactive' then 1 else 0 end)Onsite_Time,
sum(case when SUBCASE_MEASURED = '1' AND FE_TYPE = 'ASP' AND region = 'EEMEA' AND SCHEDULED_RESCHEDULED = 'Reactive' and LATE_START_CONF_INDICATOR = '0'then 1 else 0 end) Late_hours,
sum(case when SUBCASE_MEASURED = '1' AND FE_TYPE = 'ASP' AND CLOSE_MONTH = '3' AND ASP_ON_TIME = '1' then 1 else 0 end) ON_TIME
from table_Control_kpi GROUP BY ASP_NAME , TIERING_2
However along with sum i want average onsite time.
Can someone help me to club the below query with the above query
SELECT AVG(ONSITE_TIME)
FROM table_Control_kpi
WHERE SCHEDULED_RESCHEDULED = 'Reactive'
AND ASP_NAME='3D Networks'
AND SUBCASE_MEASURED = '1'
AND FE_TYPE = 'ASP'
AND CLOSE_MONTH = '3'
Maybe use a window function?
SELECT TIERING_2, ASP_NAME ,
--all the sums up there
,AVG(CASE
WHEN SCHEDULED_RESCHEDULED = 'Reactive'
AND ASP_NAME='3D Networks'
AND SUBCASE_MEASURED = '1'
AND FE_TYPE = 'ASP'
AND CLOSE_MONTH = '3'
THEN ONSITE_TIME END) OVER ()
FROM table_Control_kpi GROUP BY ASP_NAME , TIERING_2

Grouping sets is not aggregating results

I've only recently started using this function, so forgive this question if it is imbecilic.
I have an existing query, which I've realised could be helped with the use of this query to create additional group by groupings, akin to subtotals.
In this example, I am wanting to aggregate in a hierarchy like this:
Year > Month > Profit Centre > Date
An example of the results this query is bringing back
As you can see my grouping sets are returning zero.
My question is, why?
My query is below
SELECT
datepart(yyyy,overview.Date) as 'Year',
datepart(mm,overview.Date) as'Month',
overview.Date as 'Date',
overview.[Profit Centre],
overview.[Current
Year Group Bookings],
overview.[Previous Year Group Bookings],
overview.[Current Year Total Covers],
overview.[Previous Year Total Covers],
overview.[Large Group Count]
FROM
(
SELECT
DISTINCT
CONVERT(date,csd.tendered_date_time) as 'Date',
PCM.profit_center_name as 'Profit Centre',
PCD.profit_center_id,
(
SELECT count(csd2.num_covers)
FROM ig_Business..check_sales_detail csd2
INNER JOIN ig_Dimension..Profit_Center_Dimension PCD2 (NOLOCK) ON
PCD2.profit_center_dim_id = CSD2.profit_center_dim_id and PCD2.ent_id = 1
WHERE PCD2.profit_center_id = PCD.profit_center_id
AND CONVERT(date,CSD2.tendered_date_time) =
CONVERT(date,CSD.tendered_date_time)
AND CSD2.num_covers >=
(CASE
WHEN PCD.profit_center_id = '77' THEN '8'
WHEN PCD.profit_center_id = '13' THEN '10'
WHEN PCD.profit_center_id IN ('60','61','62','63','64','65') THEN '16'
WHEN PCD.profit_center_id = '14' THEN '10'
WHEN PCD.profit_center_id = '90' THEN '10'
WHEN PCD.profit_center_id = '98' THEN '8'
WHEN PCD.profit_center_id IN ('74','101') THEN '10'
WHEN PCD.profit_center_id = '194' THEN '10'
WHEN PCD.profit_center_id = '49' THEN '15'
WHEN PCD.profit_center_id IN ('20','21','22','200') THEN '8'
WHEN PCD.profit_center_id = '74' THEN '15'
WHEN PCD.profit_center_id = '26' THEN '10'
WHEN PCD.profit_center_id IN ('86','68') THEN '8'
WHEN PCD.profit_center_id IN ('40','41','42','43') THEN '8'
WHEN PCD.profit_center_id IN ('96','98','99') THEN '10'
WHEN PCD.profit_center_id = '57' THEN '10'
END)
) as 'Current Year Group Bookings',
(
SELECT count(csd2.num_covers)
FROM ig_Business..check_sales_detail csd2
INNER JOIN ig_Dimension..Profit_Center_Dimension PCD2 (NOLOCK) ON
PCD2.profit_center_dim_id = CSD2.profit_center_dim_id and PCD2.ent_id = 1
WHERE PCD2.profit_center_id = PCD.profit_center_id
AND CONVERT(date,CSD2.tendered_date_time) =
CONVERT(date,DATEADD(month,-12,CSD.tendered_date_time))
AND CSD2.num_covers >=
(CASE
WHEN PCD.profit_center_id = '77' THEN '8'
WHEN PCD.profit_center_id = '13' THEN '10'
WHEN PCD.profit_center_id IN ('60','61','62','63','64','65') THEN '16'
WHEN PCD.profit_center_id = '14' THEN '10'
WHEN PCD.profit_center_id = '90' THEN '10'
WHEN PCD.profit_center_id = '98' THEN '8'
WHEN PCD.profit_center_id IN ('74','101') THEN '10'
WHEN PCD.profit_center_id = '194' THEN '10'
WHEN PCD.profit_center_id = '49' THEN '15'
WHEN PCD.profit_center_id IN ('20','21','22','200') THEN '8'
WHEN PCD.profit_center_id = '74' THEN '15'
WHEN PCD.profit_center_id = '26' THEN '10'
WHEN PCD.profit_center_id IN ('86','68') THEN '8'
WHEN PCD.profit_center_id IN ('40','41','42','43') THEN '8'
WHEN PCD.profit_center_id IN ('96','98','99') THEN '10'
WHEN PCD.profit_center_id = '57' THEN '10'
END)
) as 'Previous Year Group Bookings',
(
SELECT ISNULL(SUM(csd2.num_covers),0)
FROM ig_Business..check_sales_detail csd2
INNER JOIN ig_Dimension..Profit_Center_Dimension PCD2 (NOLOCK) ON
PCD2.profit_center_dim_id = CSD2.profit_center_dim_id and PCD2.ent_id = 1
WHERE PCD2.profit_center_id = PCD.profit_center_id
AND CONVERT(date,CSD2.tendered_date_time) =
CONVERT(date,CSD.tendered_date_time)
AND CSD2.num_covers >=
(CASE
WHEN PCD.profit_center_id = '77' THEN '8'
WHEN PCD.profit_center_id = '13' THEN '10'
WHEN PCD.profit_center_id IN ('60','61','62','63','64','65') THEN '16'
WHEN PCD.profit_center_id = '14' THEN '10'
WHEN PCD.profit_center_id = '90' THEN '10'
WHEN PCD.profit_center_id = '98' THEN '8'
WHEN PCD.profit_center_id IN ('74','101') THEN '10'
WHEN PCD.profit_center_id = '194' THEN '10'
WHEN PCD.profit_center_id = '49' THEN '15'
WHEN PCD.profit_center_id IN ('20','21','22','200') THEN '8'
WHEN PCD.profit_center_id = '74' THEN '15'
WHEN PCD.profit_center_id = '26' THEN '10'
WHEN PCD.profit_center_id IN ('86','68') THEN '8'
WHEN PCD.profit_center_id IN ('40','41','42','43') THEN '8'
WHEN PCD.profit_center_id IN ('96','98','99') THEN '10'
WHEN PCD.profit_center_id = '57' THEN '10'
END)
) as 'Current Year Total Covers',
(
SELECT ISNULL(SUM(csd2.num_covers),0)
FROM ig_Business..check_sales_detail csd2
INNER JOIN ig_Dimension..Profit_Center_Dimension PCD2 (NOLOCK) ON
PCD2.profit_center_dim_id = CSD2.profit_center_dim_id and PCD2.ent_id = 1
WHERE PCD2.profit_center_id = PCD.profit_center_id
AND CONVERT(date,CSD2.tendered_date_time) =
CONVERT(date,DATEADD(month,-12,CSD.tendered_date_time))
AND CSD2.num_covers >=
(CASE
WHEN PCD.profit_center_id = '77' THEN '8'
WHEN PCD.profit_center_id = '13' THEN '10'
WHEN PCD.profit_center_id IN ('60','61','62','63','64','65') THEN '16'
WHEN PCD.profit_center_id = '14' THEN '10'
WHEN PCD.profit_center_id = '90' THEN '10'
WHEN PCD.profit_center_id = '98' THEN '8'
WHEN PCD.profit_center_id IN ('74','101') THEN '10'
WHEN PCD.profit_center_id = '194' THEN '10'
WHEN PCD.profit_center_id = '49' THEN '15'
WHEN PCD.profit_center_id IN ('20','21','22','200') THEN '8'
WHEN PCD.profit_center_id = '74' THEN '15'
WHEN PCD.profit_center_id = '26' THEN '10'
WHEN PCD.profit_center_id IN ('86','68') THEN '8'
WHEN PCD.profit_center_id IN ('40','41','42','43') THEN '8'
WHEN PCD.profit_center_id IN ('96','98','99') THEN '10'
WHEN PCD.profit_center_id = '57' THEN '10'
END)
) as 'Previous Year Total Covers',
(CASE
WHEN PCD.profit_center_id = '77' THEN '8'
WHEN PCD.profit_center_id = '13' THEN '10'
WHEN PCD.profit_center_id IN ('60','61','62','63','64','65') THEN '16'
WHEN PCD.profit_center_id = '14' THEN '10'
WHEN PCD.profit_center_id = '90' THEN '10'
WHEN PCD.profit_center_id = '98' THEN '8'
WHEN PCD.profit_center_id IN ('74','101') THEN '10'
WHEN PCD.profit_center_id = '194' THEN '10'
WHEN PCD.profit_center_id = '49' THEN '15'
WHEN PCD.profit_center_id IN ('20','21','22','200') THEN '8'
WHEN PCD.profit_center_id = '74' THEN '15'
WHEN PCD.profit_center_id = '26' THEN '10'
WHEN PCD.profit_center_id IN ('86','68') THEN '8'
WHEN PCD.profit_center_id IN ('40','41','42','43') THEN '8'
WHEN PCD.profit_center_id IN ('96','98','99') THEN '10'
WHEN PCD.profit_center_id = '57' THEN '10'
END) AS 'Large Group Count'
FROM ig_business..Check_Sales_Detail CSD (NOLOCK)
INNER JOIN ig_Dimension..Profit_Center_Dimension PCD (NOLOCK) ON
PCD.profit_center_dim_id = CSD.profit_center_dim_id and PCD.ent_id = 1
INNER JOIN it_cfg..Profit_Center_Master PCM (NOLOCK) ON PCM.profit_center_id
= PCD.profit_center_id and PCm.ent_id = 1
WHERE
(
(pcd.profit_center_id = '77' AND csd.num_covers > 8)
OR
(pcd.profit_center_id = '13' AND csd.num_covers >= 10)
OR
(pcd.profit_center_id IN ('60','61','62','63','64','65') AND
csd.num_covers > 16)
OR
(pcd.profit_center_id = 14 AND csd.num_covers >= 10)
OR
(pcd.profit_center_id = 90 AND csd.num_covers >= 10)
OR
(pcd.profit_center_id = 98 AND csd.num_covers >= 8)
OR
(pcd.profit_center_id IN ('74','101') AND csd.num_covers >= 10)
OR
(pcd.profit_center_id = '194' AND csd.num_covers >= 10)
OR
(pcd.profit_center_id = '49' AND csd.num_covers >= 15)
OR
(pcd.profit_center_id IN ('20','21','22','200') AND csd.num_covers >= 8)
OR
(pcd.profit_center_id = '74' AND csd.num_covers >= 15)
OR
(pcd.profit_center_id = '26' AND csd.num_covers >= 10)
OR
(pcd.profit_center_id IN ('86','68') AND csd.num_covers >= 8)
OR
(pcd.profit_center_id IN ('40','41','42','43') AND csd.num_covers >= 8)
OR
(pcd.profit_center_id IN ('96','98','99') AND csd.num_covers >= 10)
OR
(pcd.profit_center_id = '57' AND csd.num_covers >= 10)
)
AND
CSD.tendered_date_time > CONVERT(date,'2017-01-01') -- We only want
comparisons from today going forward, i.e. not historical
GROUP BY
GROUPING SETS
(
(csd.tendered_date_time, PCM.profit_center_name,PCD.profit_center_id),
(datepart(yyyy,csd.tendered_date_time),datepart(mm,csd.tendered_date_time),
pcm.profit_center_name),
()
)
) overview
ORDER BY overview.[Profit Centre] asc, CONVERT(date,overview.Date) asc
My question is, why (are the grouping sets zero)?
Because you are not using aggregate functions such as SUM() or COUNT() in a manner than can be summarised into sub-totals. You are using a set of "correlated subqueries" which do use COUNT() but by the time these are evaluated the outer query just sees those columns as data (not as aggregates).
example (untested of course):
WITH pcd AS (
SELECT *
FROM ig_Dimension..Profit_Center_Dimension pcd
WHERE (
OR (pcd.profit_center_id = '13' AND csd.num_covers >= 10)
OR (pcd.profit_center_id = 14 AND csd.num_covers >= 10) -- is it an integer? or not?
OR (pcd.profit_center_id = '26' AND csd.num_covers >= 10)
OR (pcd.profit_center_id = '49' AND csd.num_covers >= 15)
OR (pcd.profit_center_id = '57' AND csd.num_covers >= 10)
OR (pcd.profit_center_id = '74' AND csd.num_covers >= 15)
OR (pcd.profit_center_id = '77' AND csd.num_covers > 8)
OR (pcd.profit_center_id = 90 AND csd.num_covers >= 10) -- is it an integer? or not?
OR (pcd.profit_center_id = 98 AND csd.num_covers >= 8) -- is it an integer? or not?
OR (pcd.profit_center_id = '194' AND csd.num_covers >= 10)
OR (pcd.profit_center_id IN ('20', '21', '22', '200') AND csd.num_covers >= 8)
OR (pcd.profit_center_id IN ('40', '41', '42', '43') AND csd.num_covers >= 8)
OR (pcd.profit_center_id IN ('60', '61', '62', '63', '64', '65') AND csd.num_covers > 16)
OR (pcd.profit_center_id IN ('74', '101') AND csd.num_covers >= 10)
OR (pcd.profit_center_id IN ('86', '68') AND csd.num_covers >= 8)
OR (pcd.profit_center_id IN ('96', '98', '99') AND csd.num_covers >= 10)
)
AND pcd.ent_id = 1
)
SELECT
DATEPART(yyyy, csd.tendered_date_time) AS 'Year'
, DATEPART(mm, csd.tendered_date_time) AS 'Month'
, pcd.[Profit Centre]
, pcm.profit_center_name AS 'Profit Centre'
, pcd.profit_center_id
, COUNT(csd.num_covers)
FROM ig_business..Check_Sales_Detail csd
INNER JOIN pcd ON pcd.profit_center_dim_id = csd.profit_center_dim_id
INNER JOIN it_cfg..Profit_Center_Master pcm ON pcm.profit_center_id = pcd.profit_center_id
AND pcm.ent_id = 1
GROUP BY GROUPING SETS
( DATEPART(yyyy, csd.tendered_date_time) AS 'Year'
, DATEPART(mm, csd.tendered_date_time) AS 'Month'
, pcd.[Profit Centre]
, pcm.profit_center_name AS 'Profit Centre'
, pcd.profit_center_id
)
NOTE: you need to be careful about "implicit conversions", if pcd.profit_center_id is an integer then do NOT use '194', but if it is a varchar or similar then do not use integers. I also suggest you try to keep that where clause in some "order" so it is easier to read.

Union SUM SQL Must have its own alias

I have made some relative posts with the same errors, I have tried almost every solution that has been suggested.
Here is the SQL:
SELECT Sum(h.counter1 + l.counter2) AS hour_amount
FROM (
SELECT 1
FROM xp_hour h
WHERE h.account_id = '1'
AND h.hour_date = Date('2017-03-06')
AND ((
h.from_time < Time('06:00')
AND h.till_time > Time('06:00'))
OR (
h.from_time < Time('15:00')
AND h.till_time > Time('15:00'))
OR (
h.from_time = Time('06:00')
AND h.till_time = Time('15:00'))))
UNION ALL
(
SELECT 1
FROM xp_leave l
WHERE l.account_id = '1'
AND ((
l.from_datetime < Timestamp('2017-03-06 06:00')
AND l.till_datetime > Timestamp('2017-03-06 06:00'))
OR (
l.from_datetime < Timestamp('2017-03-06 15:00')
AND l.till_datetime > Timestamp('2017-03-06 15:00')))) t_union
Error
Error: Every derived table must have its own alias
Try this:
SELECT SUM(h.counter1 + l.counter2) AS hour_amount
FROM (
SELECT 1
FROM xp_hour h
WHERE h.account_id = '1' AND h.hour_date = DATE('2017-03-06') AND
(
(h.from_time < TIME('06:00') AND h.till_time > TIME('06:00')) OR
(h.from_time < TIME('15:00') AND h.till_time > TIME('15:00')) OR
(h.from_time = TIME('06:00') AND h.till_time = TIME('15:00'))
)
UNION ALL
SELECT 1
FROM xp_leave l
WHERE l.account_id = '1' AND
(
(l.from_datetime < TIMESTAMP('2017-03-06 06:00') AND
l.till_datetime > TIMESTAMP('2017-03-06 06:00')) OR
(l.from_datetime < TIMESTAMP('2017-03-06 15:00') AND
l.till_datetime > TIMESTAMP('2017-03-06 15:00'))
)
) t_union
You need to enclose the whole UNION ALL subquery in parentheses, not the individual subqueries that take part in the UNION ALL operation.
Problem is with parenthesis. 1st query is interpreted as separate question which belongs to first from.
Try this:
SELECT SUM(h.counter1 + l.counter2) AS hour_amount FROM
(SELECT 1 FROM xp_hour h WHERE h.account_id = '1' AND h.hour_date = DATE('2017-03-06') AND ((h.from_time < TIME('06:00') AND h.till_time > TIME('06:00')) OR (h.from_time < TIME('15:00') AND h.till_time > TIME('15:00')) OR (h.from_time = TIME('06:00') AND h.till_time = TIME('15:00')))
UNION ALL
(SELECT 1 FROM xp_leave l WHERE l.account_id = '1' AND ((l.from_datetime < TIMESTAMP('2017-03-06 06:00') AND l.till_datetime > TIMESTAMP('2017-03-06 06:00')) OR (l.from_datetime < TIMESTAMP('2017-03-06 15:00') AND l.till_datetime > TIMESTAMP('2017-03-06 15:00'))))) t_union
I remove the last ) from 1st query to end of union
Name a alias for the first part of the derived table before UNION ALL like you put t_union for the 2nd part.
for example:
(SELECT 1
FROM xp_hour h
WHERE h.account_id = '1'
AND h.hour_date = DATE('2017-03-06')
AND ((h.from_time < TIME('06:00')
AND h.till_time > TIME('06:00'))
OR (h.from_time < TIME('15:00')
AND h.till_time > TIME('15:00'))
OR (h.from_time = TIME('06:00')
AND h.till_time = TIME('15:00')))) as t_union_1

TSQL convert list of IP addresses to CIDR notation

Given a table with the following IP Addresses
IPAddress
-----------
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
192.168.1.6
192.168.1.7
192.168.1.8
I'm looking for the following output
Output
---------------
192.168.1.0/29
192.168.1.8/32
The closest I've come was with this:
SELECT SUBSTRING(IPAddress, 1, LEN(IPAddress) - CHARINDEX('.',REVERSE(IPAddress))), COUNT(*)
FROM IP
GROUP BY SUBSTRING(IPAddress, 1, LEN(IPAddress) - CHARINDEX('.',REVERSE(IPAddress)))
But that only gets me the subnet and # of address. Not sure how to take the next step.
You will need the subnet-mask in order to know the correct amount of host bits for your notation.
This will give you CIDR:
DECLARE #IPADDRESS VARCHAR(15) = '192.168.1.1'
,#NETMASK VARCHAR(15) = '255.255.255.0'
,#NETWORKBITS VARCHAR(3)
SET #NETWORKBITS =
CASE
WHEN #NETMASK = '255.0.0.0' THEN '8'
WHEN #NETMASK = '255.128.0.0' THEN '9'
WHEN #NETMASK = '255.192.0.0' THEN '10'
WHEN #NETMASK = '255.224.0.0' THEN '11'
WHEN #NETMASK = '255.240.0.0' THEN '12'
WHEN #NETMASK = '255.248.0.0' THEN '13'
WHEN #NETMASK = '255.252.0.0' THEN '14'
WHEN #NETMASK = '255.254.0.0' THEN '15'
WHEN #NETMASK = '255.255.0.0' THEN '16'
WHEN #NETMASK = '255.255.128.0' THEN '17'
WHEN #NETMASK = '255.255.192.0' THEN '18'
WHEN #NETMASK = '255.255.224.0' THEN '19'
WHEN #NETMASK = '255.255.240.0' THEN '20'
WHEN #NETMASK = '255.255.248.0' THEN '21'
WHEN #NETMASK = '255.255.252.0' THEN '22'
WHEN #NETMASK = '255.255.254.0' THEN '23'
WHEN #NETMASK = '255.255.255.0' THEN '24'
WHEN #NETMASK = '255.255.255.128' THEN '25'
WHEN #NETMASK = '255.255.255.192' THEN '26'
WHEN #NETMASK = '255.255.255.224' THEN '27'
WHEN #NETMASK = '255.255.255.240' THEN '28'
WHEN #NETMASK = '255.255.255.248' THEN '29'
WHEN #NETMASK = '255.255.255.252' THEN '30'
WHEN #NETMASK = '255.255.255.254' THEN '31'
WHEN #NETMASK = '255.255.255.255' THEN '32'
END
PRINT #IPADDRESS + '/' #NETWORKBITS