SQL query add new custom row dynamically - sql

Below is my SQL query which currently outputs this result:
SQL query:
SELECT
COUNT(*) AS noofuser,
[DateTime], [Date], [hour],
[Company]
FROM
LMT2_lmutilserverLicenseuser
But, I need to add extra row called 'Total' based on a column 'DateTime' as shown in the below table.

Combining the query with a group by should work, haven't been able to run but this should give the result. You can insert the result of your query in temp table (thus count(*) gets its own column) and then just do another group by on the temp table
SELECT cnt, date_time, date , hr ,company
FROM LMT2_lmutilserverLicenseuserTemp
UNION
SELECT SUM(cnt), date_time, MAX(date) , MIN(hr) , 'tot' AS company
FROM LMT2_lmutilserverLicenseuserTemp
GROUP BY date_time
ORDER BY date_time

Related

Calculate the sum of workdays until today using SQL

I have the Base Table and I am trying to get the Result Table.
I am using this code to get the two first columns of the Result Table.
The Overdue column should give the SUM of the WorkingDays until today's date.
How can I get all 3 columns in the same select statement?
;With cte as (
Select [Id] ,[Event_Id] ,[StartDate] ,[EndDate] ,[WorkingDay] From BaseTable
)
Select
Id,
SUM(WorkingDays) as Planned
From cte
Group By Id, Event_Id

Shorthand for SQL query to count records by day across many tables

I am trying to create a table to validate my data across many different tables within a dataset. I use the following SQL query to do this, but is there any way to save time copying in the names of all tables within my dataset, either in the top level SELECT statement or the sub queries?
SELECT Date, records_table1, records_table2...
FROM
(SELECT RowDate as Date, Count(RowDate) AS records_table1 FROM [project:dataset.table1] GROUP BY Date),
(SELECT RowDate as Date, Count(RowDate) AS records_table2 FROM [project:dataset.table2] GROUP BY Date),
...
select a.*, b.records_table2 from
(SELECT RowDate as Date, Count(RowDate) AS records_table1 FROM [project:dataset.table1] GROUP BY Date)a
full join
(SELECT RowDate as Date, Count(RowDate) AS records_table2 FROM [project:dataset.table2] GROUP BY Date)b
on a.[Date]=b.[Date]
You can also use union all :
select RowDate, sum(table1) as records_table1, sum(table2) as records_table2
from (select RowDate, 1 as table1, 0 as table2
from [project:dataset.table1]
union all
select RowDate, 0, 1
from [project:dataset.table2]
) t
group by RowDate;

Some two columns using alias in order by

I have this query:
select
id,
count(1) as "visits",
count(distinct visitor_id) as "visitors"
from my_table
where timestamp > '2016-01-14'
group by id
order by "visits", "visitors"
It works.
If I change to this
select
id,
count(1) as "visits",
count(distinct visitor_id) as "visitors"
from my_table
where timestamp > '2016-01-14'
group by id
order by (("visits") + ("visitors"))
I get
column "visits" does not exist
If I change to
select
id,
count(1) as "visits",
count(distinct visitor_id) as "visitors"
from my_table
where timestamp > '2016-01-14'
group by id
order by count(1) + count(distinct visitor_id)
it works again.
Why does it work for example 1 and 3, but not for example 2? Is there any way to order by the sum of two column using their aliases?
The alternatives I could think of:
Create an outer select and order it, but that would create extra code and I would like to avoid that
Recalculate the values in the order by statement. But that would make the query more complex and maybe I would lose performance due to recalculating stuff.
PS: This query is a toy-query. The real one is much more complicated. I would like to reuse the value calculated in the select statement in the order by, but all summed up together.
Expression evaluation order is not defined. If your visits + visitors expression is evaluated before aliases you will get the error shown here above.
Instead of using the alias try using the actual column also try change the type to varchar or nvarchar, and by that I mean the following:
select
id,
count(1) as "visits",
count(distinct visitor_id) as "visitors"
from my_table
where timestamp > '2016-01-14'
group by id
order by (CAST(count(1) AS VARCHAR) + CAST(count(distinct visitor_id) AS VARCHAR))

Over clause in SQL Server

I have the following query
select * from
(
SELECT distinct
rx.patid
,rx.fillDate
,rx.scriptEndDate
,MAX(datediff(day, rx.filldate, rx.scriptenddate)) AS longestScript
,rx.drugClass
,COUNT(rx.drugName) over(partition by rx.patid,rx.fillDate,rx.drugclass) as distinctFamilies
FROM [I 3 SCI control].dbo.rx
where rx.drugClass in ('h3a','h6h','h4b','h2f','h2s','j7c','h2e')
GROUP BY rx.patid, rx.fillDate, rx.scriptEndDate,rx.drugName,rx.drugClass
) r
order by distinctFamilies desc
which produces results that look like
This should mean that between the two dates in the table the patID that there should be 5 unique drug names. However, when I run the following query:
select distinct *
from rx
where patid = 1358801781 and fillDate between '2008-10-17' and '2008-11-16' and drugClass='H4B'
I have a result set returned that looks like
You can see that while there are in fact five rows returned for the second query between the dates of 2008-10-17 and 2009-01-15, there are only three unique names. I've tried various ways of modifying the over clause, all with different levels of non-success. How can I alter my query so that I only find unique drugNames within the timeframe specified for each row?
Taking a shot at it:
SELECT DISTINCT
patid,
fillDate,
scriptEndDate,
MAX(DATEDIFF(day, fillDate, scriptEndDate)) AS longestScript,
drugClass,
MAX(rn) OVER(PARTITION BY patid, fillDate, drugClass) as distinctFamilies
FROM (
SELECT patid, fillDate, scriptEndDate, drugClass,rx.drugName,
DENSE_RANK() OVER(PARTITION BY patid, fillDate, drugClass ORDER BY drugName) as rn
FROM [I 3 SCI control].dbo.rx
WHERE drugClass IN ('h3a','h6h','h4b','h2f','h2s','j7c','h2e')
)x
GROUP BY x.patid, x.fillDate, x.scriptEndDate,x.drugName,x.drugClass,x.rn
ORDER BY distinctFamilies DESC
Not sure if DISTINCT is really necessary - left it in since you've used it.

select max, min values from two tables

I have two tables. Differ in that an archive is a table and the other holds the current record. These are the tables recording sales in the company. In both we have among other fields: id, name, price of sale. I need to select from both tables, the highest and lowest price for a given name. I tried to do with the query:
select name, max (price_of_sale), min (price_of_sale)
from wapzby
union
select name, max (price_of_sale), min (price_of_sale)
from wpzby
order by name
but such an inquiry draws me two records - one of the current table, one table archival. I want to chose a name for the smallest and the largest price immediately from both tables. How do I get this query?
Here's two options (MSSql compliant)
Note: UNION ALL will combine the sets without eliminating duplicates. That's a much simpler behavior than UNION.
SELECT Name, MAX(Price_Of_Sale) as MaxPrice, MIN(Price_Of_Sale) as MinPrice
FROM
(
SELECT Name, Price_Of_Sale
FROM wapzby
UNION ALL
SELECT Name, Price_Of_Sale
FROM wpzby
) as subQuery
GROUP BY Name
ORDER BY Name
This one figures out the max and min from each table before combining the set - it may be more performant to do it this way.
SELECT Name, MAX(MaxPrice) as MaxPrice, MIN(MinPrice) as MinPrice
FROM
(
SELECT Name, MAX(Price_Of_Sale) as MaxPrice, MIN(Price_Of_Sale) as MinPrice
FROM wapzby
GROUP BY Name
UNION ALL
SELECT Name, MAX(Price_Of_Sale) as MaxPrice, MIN(Price_Of_Sale) as MinPrice
FROM wpzby
GROUP BY Name
) as subQuery
GROUP BY Name
ORDER BY Name
In SQL Server you could use a subquery:
SELECT [name],
MAX([price_of_sale]) AS [MAX price_of_sale],
MIN([price_of_sale]) AS [MIN price_of_sale]
FROM (
SELECT [name],
[price_of_sale]
FROM [dbo].[wapzby]
UNION
SELECT [name],
[price_of_sale]
FROM [dbo].[wpzby]
) u
GROUP BY [name]
ORDER BY [name]
Is this more like what you want?
SELECT
a.name,
MAX (a.price_of_sale),
MIN (a.price_of_sale) ,
b.name,
MAX (b.price_of_sale),
MIN (b.price_of_sale)
FROM
wapzby a,
wpzby b
ORDER BY
a.name
It's untested but should return all your records on one row without the need for a union
SELECT MAX(value) FROM tabl1 UNION SELECT MAX(value) FROM tabl2;
SELECT MIN(value) FROM tabl1 UNION SELECT MIN(value) FROM tabl2;
SELECT (SELECT MAX(value) FROM table1 WHERE trn_type='CSL' and till='TILL01') as summ, (SELECT MAX(value) FROM table2WHERE trn_type='CSL' and till='TILL01') as summ_hist