EntitySQL 'IN subquery - subquery

I have the following T-SQL:
SELECT Cust.[CompanyName]
FROM Customers AS Cust
WHERE
(
Cust.[CompanyName] IN (SELECT CustSQ1.[CompanyName] AS [Customer Company name]
FROM Customers AS CustSQ1
WHERE
(
CustSQ1.Country = 'Argentina' )
) )
How do I do the same in EntitySQL?

I found the solution. Corresponding EntitySQL is:
"SELECT Cust.[CompanyName] FROM (SELECT CustSQ1.[CompanyName] FROM Customers AS CustSQ1 WHERE ( CustSQ1.Country = 'Argentina' )) AS Cust"

Related

SQL - HELP - Write a query to get the Full name, email id, phone of tenants who are married and paying rent > 9000 using subqueries

I have two tables from which the queries to be executed below is the query which have written, need help in joining the link between the query
select FIRST_NAME+ ' '+ LAST_NAME as FULL_NAME,PHONE,EMAIL
FROM PROFILES
WHERE PROFILE_ID IN
((
SELECT PROFILE_ID
FROM PROFILES
WHERE MARITIAL_STATUS= 'Y' ) and
( SELECT PROFILE_ID
FROM TENANCY_HISTORIES
WHERE RENT> '9000'));
You are using and in the list of ID's output for the in clause. Try as following:
select FIRST_NAME+ ' '+ LAST_NAME as FULL_NAME,PHONE,EMAIL
FROM PROFILES
WHERE
(PROFILE_ID IN
(
SELECT PROFILE_ID
FROM PROFILES
WHERE MARITIAL_STATUS= 'Y' ) or PROFILE_ID IN
( SELECT PROFILE_ID
FROM TENANCY_HISTORIES
WHERE RENT> '9000'));

Am getting operand clash error when running a datawarehouse compatible script

Hi I am getting an error like this: Operand type clash: date is incompatible with int.
Below is my query which I am running on a SQL Server:
CREATE TABLE val.census_last_month
WITH(
DISTRIBUTION = ROUND_ROBIN
, CLUSTERED COLUMNSTORE INDEX
)
AS
SELECT
dt_mydate AS dt_census,
(SELECT count(DISTINCT encounter_id)
FROM prod.encounter
WHERE encounter_type = 'Inpatient' AND (ts_admit BETWEEN dt_mydate - 30 AND dt_mydate) AND
(ts_discharge IS NULL OR ts_discharge > dt_mydate)) AS census,
(SELECT count(DISTINCT encounter_id)
FROM prod.encounter
WHERE encounter_type = 'Inpatient' AND cast(ts_admit AS DATE) = dt_mydate) AS admits,
(SELECT count(DISTINCT encounter_id)
FROM prod.encounter
WHERE encounter_type = 'Inpatient' AND cast(ts_discharge AS DATE) = dt_mydate) AS discharges
FROM ref.calendar_day
WHERE ref.calendar_day.dt_mydate BETWEEN (cast(getdate() as date) - 30) AND cast(getdate() as date);
You need to use dateadd function. See details here. https://learn.microsoft.com/en-us/sql/t-sql/functions/dateadd-transact-sql?view=sql-server-2017
There are multiple issues with this script, however can you confirm the datatypes starting "ts_" are dates stored as integers in the format yyyyMMdd and datatypes starting "dt_" are DATE?
Based on these assumptions, this is my attempted rewrite:
SELECT dt_mydate AS dt_census,
(
SELECT COUNT( DISTINCT encounter_id )
FROM prod.encounter
WHERE encounter_type = 'Inpatient' AND ( CAST( CAST( ts_admit AS CHAR(8) ) AS DATE ) BETWEEN DATEADD( day, -30, dt_mydate ) AND dt_mydate )
AND ( ts_discharge IS NULL OR CAST( CAST( ts_discharge AS CHAR(8) ) AS DATE ) > dt_mydate)
) AS census,
(
SELECT COUNT( DISTINCT encounter_id )
FROM prod.encounter
WHERE encounter_type = 'Inpatient' AND CAST( CAST( ts_admit AS CHAR(8) ) AS DATE ) = dt_mydate
) AS admits,
(
SELECT COUNT( DISTINCT encounter_id )
FROM prod.encounter
WHERE encounter_type = 'Inpatient'
AND CAST( CAST( ts_discharge AS CHAR(8) ) AS DATE ) = dt_mydate
) AS discharges
FROM ref.calendar_day
WHERE ref.calendar_day.dt_mydate BETWEEN CAST ( DATEADD( day, -30, GETDATE() ) AS DATE ) AND CAST( GETDATE() AS DATE );
If either of my assumptions are incorrect, please let me know and I will update the script.

Recursive Relationship Query

I am looking to implement graph tables to map the role hierarchy for my application in Azure SQL. The graph will look like a tree if it is laid out. With the parent being able to manage any role that falls beneath it on the tree.
So I have a roles node table and a canmanage edge table.
I am familiar with querying the first level and the second level of relationships, however I need to have a query where I can put in any role and receive a list of all the children that fall under it.
I am familiar with this sort of thing in NEO4J, but I have not found any documentation on how to accomplish this in Azure SQL.
How do I go about running a recursive query to get all the child roles give a specific role name or id?
This is possible from SQL Server 2017 and Azure SQL DB using the new graph database capabilities and the new MATCH clause to model this type of relationship. Unfortunately in v1 polymorphism and transitive closure are not natively included but are possible using recursive queries. If you look at the last query, it keep the parameter you input as the top-level manager and iterates over the rest.
A sample script:
USE tempdb
GO
-- NODES
DROP TABLE IF EXISTS dbo.roles
-- EDGES
DROP TABLE IF EXISTS dbo.canManage
DROP TABLE IF EXISTS dbo.isManagedBy
GO
CREATE TABLE dbo.roles (
roleId INT PRIMARY KEY,
roleName VARCHAR(20) UNIQUE NOT NULL
) AS NODE
CREATE TABLE dbo.canManage AS EDGE;
CREATE TABLE dbo.isManagedBy AS EDGE;
GO
-- Populate node table
INSERT INTO dbo.roles ( roleId, roleName )
VALUES
( 1, 'CEO' ),
( 2, 'VP 1' ),
( 3, 'VP 2' ),
( 4, 'Sales Manager 1' ),
( 5, 'Sales Manager 2' ),
( 6, 'Ops Manager 1' ),
( 7, 'Ops Manager 2' ),
( 8, 'Sales Lead 1' ),
( 9, 'Salesperson 1' ),
( 10, 'Salesperson 2' ),
( 11, 'Salesperson 3' )
GO
-- Populate edge table
INSERT INTO dbo.canManage ( $from_id, $to_id )
SELECT ceo.$node_id, VPs.$node_id
FROM dbo.roles ceo
CROSS JOIN dbo.roles VPs
WHERE ceo.roleName = 'CEO'
AND VPs.roleName Like 'VP%'
-- VP 1 manages Sales Managers
INSERT INTO dbo.canManage ( $from_id, $to_id )
SELECT a.$node_id, b.$node_id
FROM dbo.roles a
CROSS JOIN dbo.roles b
WHERE a.roleName = 'VP 1'
AND b.roleName Like 'Sales Manager%'
-- VP 2 manages Ops Managers
INSERT INTO dbo.canManage ( $from_id, $to_id )
SELECT a.$node_id, b.$node_id
FROM dbo.roles a
CROSS JOIN dbo.roles b
WHERE a.roleName = 'VP 2'
AND b.roleName Like 'Ops Manager%'
-- Sales Manger 1 manages Sales Leads
INSERT INTO dbo.canManage ( $from_id, $to_id )
SELECT a.$node_id, b.$node_id
FROM dbo.roles a
CROSS JOIN dbo.roles b
WHERE a.roleName = 'Sales Manager 1'
AND b.roleName Like 'Sales Lead%'
-- Sales Leads 1 manages all salespersons
INSERT INTO dbo.canManage ( $from_id, $to_id )
SELECT a.$node_id, b.$node_id
FROM dbo.roles a
CROSS JOIN dbo.roles b
WHERE a.roleName = 'Sales Lead 1'
AND b.roleName Like 'Salesperson%'
-- Create the inverse edge / relationship
INSERT INTO dbo.isManagedBy ( $from_id, $to_id )
SELECT $to_id, $from_id
FROM dbo.canManage
GO
-- Now write the graph queries:
-- Manages
SELECT FORMATMESSAGE( '%s manages %s', r1.roleName, r2.roleName ) manages
FROM dbo.roles r1, dbo.canManage canManage, dbo.roles r2
WHERE MATCH ( r1-(canManage)->r2 )
-- Same manager
SELECT FORMATMESSAGE( '%s and %s have the same manager %s', r1.roleName, r3.roleName, r2.roleName )
FROM dbo.roles r1, dbo.isManagedBy m1, dbo.roles r2, dbo.isManagedBy m2, dbo.roles r3
WHERE MATCH ( r1-(m1)->r2<-(m2)-r3 )
AND r1.$node_id < r3.$node_id
-- Recursive
-- walk the tree ... CEO manages everyone ...
;WITH cte AS (
SELECT 1 xlevel, r1.roleName manager, r2.roleName managed
FROM dbo.roles r1, dbo.canManage canManage, dbo.roles r2
WHERE MATCH ( r1-(canManage)->r2 )
AND r1.roleName = 'CEO'
UNION ALL
SELECT c.xlevel + 1, r1.roleName, r2.roleName
FROM cte c, dbo.roles r1, dbo.canManage canManage, dbo.roles r2
WHERE c.managed = r1.roleName
AND MATCH ( r1-(canManage)->r2 )
)
SELECT *
FROM cte
ORDER BY xlevel, manager, managed
;WITH cte AS (
SELECT 1 xlevel, r1.roleName manager, r2.roleName managed
FROM dbo.roles r1, dbo.canManage canManage, dbo.roles r2
WHERE MATCH ( r1-(canManage)->r2 )
AND r1.roleName = 'CEO'
UNION ALL
SELECT c.xlevel + 1, c.manager, r2.roleName
FROM cte c, dbo.roles r1, dbo.canManage canManage, dbo.roles r2
WHERE c.managed = r1.roleName
AND MATCH ( r1-(canManage)->r2 )
)
SELECT *
FROM cte
ORDER BY xlevel, manager, managed

PowerPivot Filter Function

In PowerPivot Excel 2016 I write a formula to summarize year to date sales using filter function as below:
SalesYTD:=CALCULATE (
[Net Sales],
FILTER (
ALL ( Sales),
'sales'[Year] = MAX ( 'Sales'[Year] )
&& 'Sales'[Date] <= MAX ( 'Sales'[Date] )
)
)
And it's work perfectly, now in my data I have a field called "Channel" which I want to filter it in my pivot table but it won't works!
Does anybody knows how should I fix this formula?!
Thanks in advance...
Try:
SalesYTD:=CALCULATE (
[Net Sales],
FILTER (
ALLEXCEPT ( 'Sales', 'Sales'[Channel] ),
'sales'[Year] = MAX ( 'Sales'[Year] )
&& 'Sales'[Date] <= MAX ( 'Sales'[Date] )
)
)
ALLEXCEPT removes all context filters in the table except filters that have been applied to the specified columns, in this case [Channel] column.
Let me know if this helps.

Dynamic Pivot without Null value

This is a dynamic crosstab query in Northwind database:
DECLARE #COUNTRY NVARCHAR(MAX) ='', #COUNTRY2 NVARCHAR(MAX)
SELECT #COUNTRY = #COUNTRY + QUOTENAME(Country)+', '
FROM Customers
GROUP BY Country
SET #COUNTRY= LEFT(#COUNTRY, LEN(#COUNTRY)-1)
SET #COUNTRY2 = REPLACE(#COUNTRY, ',' , '+')
DECLARE #SQL NVARCHAR(MAX)
SET #SQL = 'SELECT * , '+#COUNTRY2+' AS TOTAL
FROM (SELECT E.EmployeeID, E.LastName,
ISNULL( OD.Quantity, 0)* ISNULL(OD.[UnitPrice],0) QU,
O.ShipCountry AS CO
FROM Orders O JOIN Employees E ON O.EmployeeID = E.EmployeeID
JOIN [dbo].[Order Details] OD ON OD.OrderID = O.OrderID) AS T
PIVOT(SUM(QU) FOR CO IN ('+#COUNTRY+')) AS PVT
ORDER BY 1'
EXEC(#SQL)
I need to change the code in a way that have Null values replaced by 0.
DECLARE #COUNTRY NVARCHAR(MAX) = '' ,
#COUNTRY2 NVARCHAR(MAX);
SELECT #COUNTRY = #COUNTRY + COALESCE(QUOTENAME(Country) + ', ', '')
FROM Customers
WHERE EXISTS ( SELECT *
FROM [Orders] AS [o]
WHERE o.[CustomerID] = Customers.[CustomerID] )
GROUP BY Country;
SET #COUNTRY = LEFT(#COUNTRY, LEN(#COUNTRY) - 1);
SET #COUNTRY2 = REPLACE(#COUNTRY, ',', '+');
DECLARE #SQL NVARCHAR(MAX);
SET #SQL = 'SELECT * , ' + #COUNTRY2 +
' AS TOTAL
FROM (
SELECT oe.EmployeeID, oe.LastName, oe.ShipCountry AS CO,
COALESCE(OD.Quantity * OD.UnitPrice, 0) AS QU
FROM (
SELECT EmployeeID, LastName, ShipCountry
FROM (
SELECT DISTINCT
ShipCountry
FROM Orders
) o ,
Employees
) oe
LEFT JOIN Orders O ON O.EmployeeID = oe.EmployeeID AND
[oe].[ShipCountry] = [O].[ShipCountry]
LEFT JOIN [Order Details] OD ON OD.OrderID = O.OrderID
) AS T
PIVOT(SUM(QU) FOR CO IN (' + #COUNTRY + ')) AS PVT
ORDER BY 1';
EXEC(#SQL);
You need to change the SELECT * to:
SELECT ISNULL(Argentina,0) AS 'Argentina' , INSNULL(Belgium,0) AS 'Belgium' , ....
Ofcourse, you would need to change your dynamic query to reflect the ISNULL functions.
Good Luck

Resources