SQL UNION Not Working - sql

I'm using SQL Server 2014 and have two table: ApplicationProjectLO and V_SIP_ALLSTAFF:
Table ApplicationProjectLO:
|---------------------|---------------------------|
| StaffEmailId | Type |
|---------------------|---------------------------|
| chinkim1 | L |
|---------------------|---------------------------|
| kandiah1 | A |
|---------------------|---------------------------|
Table V_SIP_ALLSTAFF
|---------------------|----------------|-------------------|---------------|
| lOGINID | displayname | Email Address |MainOfficeTelNo|
|---------------------|----------------|---------------- |-------------- |
| chinkim1 | james | 1 | 5 |
|---------------------|----------------|---------------- |---------------|
| kandiah1 | hoho | 2 | 8 |
|---------------------|----------------|---------------- |---------------|
I would like to display the information based on 'Type'.
So if the StaffEmailId match the LONGINID and the type is A, the information of type A (that is hoho, 2, and 8) must be displayed, and if type is L then it james, 1, and 5 must be displayed.
I tried to use UNION and UNION ALL to run two select statement in one query but it only return type=L result based on this query:
SELECT
vsa.displayname NameofLiaisonOfficer,
vsa.EmailAddress LOEmail,
'(65)' +' '+ convert(varchar, vsa.MainOfficeTelNo ) as LOContactNo,
vsa.MainOfficeTelNo GeneralOfficeConatctNo
FROM ApplicationProjectLo ap
INNER JOIN V_SIP_ALLSTAFF vsa ON ap.StaffEmailId = vsa.LOGINID
WHERE ap.Type = 'L'
UNION ALL
SELECT
vsa.displayname NameofAlternateLiaisonOfficer,
vsa.EmailAddress AlternateLOEmail,
'(65)' +' '+ convert(varchar, vsa.MainOfficeTelNo ) as AlternateLOContactNo,
vsa.MainOfficeTelNo GeneralOfficeConatctNo
FROM ApplicationProjectLo ap
INNER JOIN V_SIP_ALLSTAFF vsa ON ap.StaffEmailId = vsa.LOGINID
WHERE ap.Type = 'A'
MVC View:
<tr>
<td colspan="3">
<strong>Name of Liaison Officer</strong>
<br />
<br /> #Html.DisplayFor(m => m.TPInformationDetails.NameofLiaisonOfficer)
</td>
#*
<td>
<strong>Room Number</strong>
<br />
<br />
</td>*#
<td>
<strong>Contact Number</strong>
<br />
<br /> #Html.DisplayFor(m => m.TPInformationDetails.LOContactNo)
</td>
<td>
<strong>Email Address</strong>
<br />
<br /> #Html.DisplayFor(m => m.TPInformationDetails.LOEmail)
</td>
</tr>
<!-- Table Row -->
<tr class="even">
<td colspan="3">
<strong>Name of Alternate Liaison Officer</strong>
<br />
<br /> #Html.DisplayFor(m => m.TPInformationDetails.NameofAlternateLiaisonOfficer)
</td>
<td>
<strong>Contact Number</strong>
<br />
<br /> #Html.DisplayFor(m => m.TPInformationDetails.AlternateLOContactNo)
</td>
<td>
<strong>Email Address</strong>
<br />
<br /> #Html.DisplayFor(m => m.TPInformationDetails.AlternateLOEmail)
</td>
</tr>
<!-- Table Row -->

Just dispense wth the WHERE:
SELECT vsa.displayname as NameofLiaisonOfficer,
vsa.EmailAddress LOEmail,
'(65)' +' '+ convert(varchar, vsa.MainOfficeTelNo ) as LOContactNo,
vsa.MainOfficeTelNo GeneralOfficeConatctNo
FROM ApplicationProjectLo ap INNER JOIN
V_SIP_ALLSTAFF vsa
ON ap.StaffEmailId = vsa.LOGINID;
Or use a WHERE that includes both types:
SELECT vsa.displayname as NameofLiaisonOfficer,
vsa.EmailAddress LOEmail,
'(65)' +' '+ convert(varchar, vsa.MainOfficeTelNo ) as LOContactNo,
vsa.MainOfficeTelNo GeneralOfficeConatctNo
FROM ApplicationProjectLo ap INNER JOIN
V_SIP_ALLSTAFF vsa
ON ap.StaffEmailId = vsa.LOGINID;
WHERE ap.Type IN ('A', 'L');
That said, it is unclear why your query -- although over-complicated -- is not returning both types. One possibility is that you are using a national character set and the "A" is not really an "A".

Use the below query to display the result with type 'L' and 'A'.
SELECT
vsa.displayname NameofLiaisonOfficer,
vsa.EmailAddress LOEmail,
'(65)' +' '+ convert(varchar, vsa.MainOfficeTelNo ) as LOContactNo,
vsa.MainOfficeTelNo GeneralOfficeConatctNo
FROM ApplicationProjectLo ap
INNER JOIN V_SIP_ALLSTAFF vsa ON ap.StaffEmailId = vsa.LOGINID
WHERE ap.Type IN ('L','A')
ORDER BY ap.Type desc

SELECT
vsa.displayname NameofLiaisonOfficer,
vsa.EmailAddress LOEmail,
'(65)' +' '+ convert(varchar, vsa.MainOfficeTelNo ) as LOContactNo,
vsa.MainOfficeTelNo GeneralOfficeConatctNo
FROM ApplicationProjectLo ap
INNER JOIN V_SIP_ALLSTAFF vsa ON ap.StaffEmailId = vsa.LOGINID
WHERE ap.Type IN ('A', 'L')

You need a JOIN, not an UNION. JOIN combines columns from two tables based on common key field(s).
SELECT a.field1, b.field1, b.field2 FROM table1 a JOIN table2 b ON a.keyfield=b.keyfield;

const string _sqlODetails = #"SELECT vsa.displayname NameofLiaisonOfficer,
vsa.EmailAddress LOEmail,
'(65)' +' '+ convert(varchar, vsa.MainOfficeTelNo ) as LOContactNo,
vsa.MainOfficeTelNo GeneralOfficeConatctNo
FROM ApplicationProjectLo ap
INNER JOIN V_SIP_ALLSTAFF vsa ON ap.StaffEmailId = vsa.LOGINID
WHERE ap.Type = 'L'";
using (var connection = Db.SqlServer())
{
tpOdetails = connection
.Query<TPInformationDetails>(_sqlODetails)
.FirstOrDefault();
}
const string _sqlADetails = #"SELECT vsa.displayname NameofAlternateLiaisonOfficer,
vsa.EmailAddress AlternateLOEmail,
'(65)' +' '+ convert(varchar, vsa.MainOfficeTelNo ) as AlternateLOContactNo,
vsa.MainOfficeTelNo GeneralOfficeConatctNo
FROM ApplicationProjectLo ap
INNER JOIN V_SIP_ALLSTAFF vsa ON ap.StaffEmailId = vsa.LOGINID
WHERE ap.Type = 'A'";
using (var connection = Db.SqlServer())
{
tpAdetails = connection
.Query<TPInformationDetails>(_sqlADetails)
.FirstOrDefault();
}

Related

How can I make all values of one identifier the same based a on value in a row?

SELECT a.IDENTIFIER,
a.NAME,
a.CATEGORY,
b.IDENTIFIER_TYPE,
b.NAME,
CASE
WHEN b.IDENTIFIER_TYPE = 111 THEN 'PRESENT'
ELSE 'NOT PRESENT'
END AS HAS111
FROM TABLE_A a
LEFT JOIN IDENTIFIER_TYPE_TABLE b ON a.IDENTIFIER = b.IDENTIFIER
WHERE a.IDENTIFIER IN (1, 2, 3, 4)
;
Here is the code I'm using, and the data I'm getting is:
But I want the data to look like this:
Basically, I need this:
td {
text-align: center;
}
<table>
<tbody>
<tr>
<td>IDENTIFIER</td>
<td>NAME</td>
<td>CATEGORY</td>
<td>IDENTIFIER_TYPE</td>
<td>HAS111</td>
</tr>
<tr>
<td>123</td>
<td>item123</td>
<td>1</td>
<td>778</td>
<td>not present</td>
</tr>
<tr>
<td>123</td>
<td>item123</td>
<td>1</td>
<td>127</td>
<td>not present</td>
</tr>
<tr>
<td>123</td>
<td>item123</td>
<td>1</td>
<td>137</td>
<td>not present</td>
</tr>
<tr>
<td>456</td>
<td>item456</td>
<td>1</td>
<td>122</td>
<td>not present</td>
</tr>
<tr>
<td>456</td>
<td>item456</td>
<td>2</td>
<td>87</td>
<td>not present</td>
</tr>
<tr>
<td>456</td>
<td>item456</td>
<td>2</td>
<td>444</td>
<td>not present</td>
</tr>
<tr>
<td>789</td>
<td>item789</td>
<td>2</td>
<td>289</td>
<td>present</td>
</tr>
<tr>
<td>789</td>
<td>item789</td>
<td>2</td>
<td>111</td>
<td>present</td>
</tr>
<tr>
<td>789</td>
<td>item789</td>
<td>2</td>
<td>75</td>
<td>present</td>
</tr>
</tbody>
</table>
You see item789 has 111 in one of the rows, therefore I need all the other rows to say "present" for item789. The others don't have 111, so they have no 111 present. Does this make sense?
You can use EXISTS :
SELECT a.IDENTIFIER, a.NAME, a.CATEGORY, b.IDENTIFIER_TYPE, b.NAME,
(CASE WHEN EXISTS (SELECT 1
FROM IDENTIFIER_TYPE_TABLE b1
WHERE a.IDENTIFIER = b1.IDENTIFIER AND
b1.IDENTIFIER_TYPE = 111
)
THEN 'PRESENT' ELSE 'NOT PRESENT'
END) AS HAS111
FROM TABLE_A a LEFT JOIN
IDENTIFIER_TYPE_TABLE b
ON a.IDENTIFIER = b.IDENTIFIER
WHERE a.IDENTIFIER IN (1, 2, 3, 4);
Use window functions:
SELECT a.IDENTIFIER, a.NAME, a.CATEGORY,
b.IDENTIFIER_TYPE, b.NAME,
(CASE WHEN b.num_111 > 0 THEN 'PRESENT'
ELSE 'NOT PRESENT'
END) AS HAS111
FROM TABLE_A a LEFT JOIN
(SELECT b.*,
SUM(CASE WHEN b.IDENTIFIER_TYPE = 111 THEN 1 ELSE 0 END) OVER (PARTITION BY b.IDENTIFIER) as num_111
FROM IDENTIFIER_TYPE_TABLE b
) b
ON a.IDENTIFIER = b.IDENTIFIER
WHERE a.IDENTIFIER IN (1, 2, 3, 4);
Or don't use a subquery:
SELECT a.IDENTIFIER, a.NAME, a.CATEGORY,
b.IDENTIFIER_TYPE, b.NAME,
(CASE WHEN SUM(CASE WHEN b.IDENTIFIER_TYPE = 111 THEN 1 ELSE 0 END) > 0 THEN 'PRESENT'
ELSE 'NOT PRESENT'
END) AS HAS111
FROM TABLE_A a LEFT JOIN
IDENTIFIER_TYPE_TABLE b
ON a.IDENTIFIER = b.IDENTIFIER
WHERE a.IDENTIFIER IN (1, 2, 3, 4);
You will want to left join to your table again for just presents:
SELECT a.IDENTIFIER,
a.NAME,
a.CATEGORY,
b.IDENTIFIER_TYPE,
b.NAME,
iif( b.identifier is null,'Not Present','Present') as HAS111
FROM TABLE_A a
left join (Select distinct identifier table_A where type = 111) b on a.identifier=b.identifier

selecting random rows from table

I have the following query, returning over 100 000 rows, How do I select random 8000 rows from(for example) vw_client_uli_member_type? Can someone provide an example on my query?
SELECT ind_cst_key,
ind_int_code as 'Individual Type',
ind_first_name as 'First Name',
ind_last_name as 'Last Name',
cst_recno as 'Member ID',
cst_eml_address_dn as 'Email Address',
adr_city as 'City',
adr_state as 'State' ,
adr_country as 'Country',
cst_org_name_dn as 'Company',
cst_ixo_title_dn as 'Job Title',
mem_member_type as 'Member Type'
FROM
co_individual WITH (NOLOCK)
JOIN co_individual_ext WITH (NOLOCK) ON ind_cst_key_ext=ind_cst_key
JOIN co_customer WITH (NOLOCK) ON cst_key=ind_cst_key and ind_delete_flag=0
and ind_deceased_flag=0
LEFT JOIN co_customer_x_address WITH (NOLOCK) ON cst_cxa_key=cxa_key
LEFT JOIN co_address WITH (NOLOCK) ON adr_key=cxa_adr_key
LEFT JOIN vw_client_uli_member_type WITH (NOLOCK) ON cst_key=mem_cst_key
WHERE mem_member_type Is Null AND adr_country = N'UNITED STATES' AND ind_deceased_flag != 1 AND ind_key_leader_flag_ext != 1 AND ind_int_code != N'Staff' AND ind_int_code != N'Spouse' AND ind_int_code != N'Press'
ORDER BY adr_country DESC
You can just add to yours query:
SELECT TOP 8000 (columns) FROM table
ORDER BY NEWID()
That should work.
This is what your code looks like after #brunofernandes suggested
SELECT top 8000 ind_cst_key,
ind_int_code as 'Individual Type',
ind_first_name as 'First Name',
ind_last_name as 'Last Name',
cst_recno as 'Member ID',
cst_eml_address_dn as 'Email Address',
adr_city as 'City',
adr_state as 'State' ,
adr_country as 'Country',
cst_org_name_dn as 'Company',
cst_ixo_title_dn as 'Job Title',
mem_member_type as 'Member Type'
FROM
co_individual WITH (NOLOCK)
JOIN co_individual_ext WITH (NOLOCK) ON ind_cst_key_ext=ind_cst_key
JOIN co_customer WITH (NOLOCK) ON cst_key=ind_cst_key and ind_delete_flag=0
and ind_deceased_flag=0
LEFT JOIN co_customer_x_address WITH (NOLOCK) ON cst_cxa_key=cxa_key
LEFT JOIN co_address WITH (NOLOCK) ON adr_key=cxa_adr_key
LEFT JOIN vw_client_uli_member_type WITH (NOLOCK) ON cst_key=mem_cst_key
WHERE mem_member_type Is Null AND adr_country = N'UNITED STATES' AND ind_deceased_flag != 1 AND ind_key_leader_flag_ext != 1 AND ind_int_code != N'Staff' AND ind_int_code != N'Spouse' AND ind_int_code != N'Press'
ORDER BY NEWID(), adr_country DESC

Add Subtotal & Total to Pivot

I have the following query
SELECT [Acct], [Customer], [Code], [Description], [Value], [Sale Person],
[Region], [Store Type], ISNULL([2016], 0) AS '2016', ISNULL([2017],0) AS
'2017'
FROM
(
SELECT CUCODE AS 'Acct', CUNAME AS 'Customer', STKCODE AS 'Code', STKNAME AS 'Description', SUM(OD_QTYORD) AS 'Packs Ordered'
, OD_GROSS AS 'Value', CUSORT AS 'Sale Person', LEFT(CUUSER1,3) AS 'Region', DATEPART(yyyy, OD_DATE) AS 'Year', OH_USER2 AS 'Store Type'
FROM STK_STOCK
INNER JOIN ORD_DETAIL ON STK_STOCK.STKCODE=ORD_DETAIL.OD_STOCK_CODE
INNER JOIN ORD_HEADER ON OD_ORDER_NUMBER=OH_ORDER_NUMBER
INNER JOIN SL_ACCOUNTS ON OH_ACCOUNT=CUCODE
WHERE STKCODE IN ('76958', '27225', '27221', '26962', '26959', '26961', '27226', '26963', '26960')
AND OD_QTYORD > 0
AND CUCODE != 'Z9997'
GROUP BY CUCODE, CUNAME, STKCODE, STKNAME, OD_GROSS, CUSORT, CUUSER1, OD_DATE, OH_USER2
) AS SourceTable
PIVOT
(
SUM([Packs Ordered])
FOR [Year] IN ([2016], [2017])
) AS PivotTable;
The output looks great but I want a subtotal for each 'Acct' and a Grand Total for the whole thing.
Can anyone help with this?
You can use group by grouping sets as below:
SELECT [Acct], [Customer], [Code], [Description], [Value], [Sale Person],
[Region], [Store Type], sum([2016]) as [2016], sum([2017]) as [2017] FROM
(
SELECT [Acct], [Customer], [Code], [Description], [Value], [Sale Person],
[Region], [Store Type], ISNULL([2016], 0) AS '2016', ISNULL([2017],0) AS
'2017'
FROM
(
SELECT CUCODE AS 'Acct', CUNAME AS 'Customer', STKCODE AS 'Code', STKNAME AS 'Description', SUM(OD_QTYORD) AS 'Packs Ordered'
, OD_GROSS AS 'Value', CUSORT AS 'Sale Person', LEFT(CUUSER1,3) AS 'Region', DATEPART(yyyy, OD_DATE) AS 'Year', OH_USER2 AS 'Store Type'
FROM STK_STOCK
INNER JOIN ORD_DETAIL ON STK_STOCK.STKCODE=ORD_DETAIL.OD_STOCK_CODE
INNER JOIN ORD_HEADER ON OD_ORDER_NUMBER=OH_ORDER_NUMBER
INNER JOIN SL_ACCOUNTS ON OH_ACCOUNT=CUCODE
WHERE STKCODE IN ('76958', '27225', '27221', '26962', '26959', '26961', '27226', '26963', '26960')
AND OD_QTYORD > 0
AND CUCODE != 'Z9997'
GROUP BY CUCODE, CUNAME, STKCODE, STKNAME, OD_GROSS, CUSORT, CUUSER1, OD_DATE, OH_USER2
) AS SourceTable
PIVOT
(
SUM([Packs Ordered])
FOR [Year] IN ([2016], [2017])
) AS PivotTable
) a
group by GROUPING SETS ( [Acct], [Customer], [Code], [Description], [Value], [Sale Person],
[Region], [Store Type] )
ORDER BY [Acct], [Customer], [Code], [Description], [Value], [Sale Person],
[Region], [Store Type];
Based on Kannan Kandasamy's reply I got this which worked beautifully:
SELECT (CASE
WHEN GROUPING([Acct])=0 AND
GROUPING([Customer]) = 1 AND
GROUPING([Code]) = 1 AND
GROUPING([Description]) = 1 AND
GROUPING([Sale Person]) = 1 AND
GROUPING([Region]) = 1 AND
GROUPING([Store Type]) = 1
THEN 'Total '+ [Acct]
WHEN GROUPING([Acct])=1 AND
GROUPING([Customer]) = 1 AND
GROUPING([Code]) = 1 AND
GROUPING([Description]) = 1 AND
GROUPING([Sale Person]) = 1 AND
GROUPING([Region]) = 1 AND
GROUPING([Store Type]) = 1
THEN 'Total'
ELSE [Acct]
END) AS Acct , ISNULL([Customer],'') AS 'Customer', ISNULL([Code],'') AS 'Code', ISNULL([Description],'') AS 'Description', SUM(ISNULL([Value],'')) AS 'Value', ISNULL([Sale Person],'') AS 'Sales Person',
ISNULL([Region],'') AS 'Region', ISNULL([Store Type],'') AS 'Store Type', SUM([2016]) AS '2016', SUM([2017]) AS '2017'
FROM
(
SELECT [Acct], [Customer], [Code], [Description], [Value], [Sale Person],
[Region], [Store Type], ISNULL([2016], 0) AS '2016', ISNULL([2017],0) AS
'2017'
FROM
(
SELECT CUCODE AS 'Acct', CUNAME AS 'Customer', STKCODE AS 'Code', STKNAME AS 'Description', SUM(OD_QTYORD) AS 'Packs Ordered'
, OD_GROSS AS 'Value', CUSORT AS 'Sale Person', LEFT(CUUSER1,3) AS 'Region', DATEPART(yyyy, OD_DATE) AS 'Year', OH_USER2 AS 'Store Type'
FROM STK_STOCK
INNER JOIN ORD_DETAIL ON STK_STOCK.STKCODE=ORD_DETAIL.OD_STOCK_CODE
INNER JOIN ORD_HEADER ON OD_ORDER_NUMBER=OH_ORDER_NUMBER
INNER JOIN SL_ACCOUNTS ON OH_ACCOUNT=CUCODE
WHERE STKCODE IN ('76958', '27225', '27221', '26962', '26959', '26961', '27226', '26963', '26960')
AND OD_QTYORD > 0
AND CUCODE != 'Z9997'
GROUP BY CUCODE, CUNAME, STKCODE, STKNAME, OD_GROSS, CUSORT, CUUSER1, OD_DATE, OH_USER2
) AS SourceTable
PIVOT
(
SUM([Packs Ordered])
FOR [Year] IN ([2016], [2017])
) AS PivotTable
) a
group by GROUPING SETS (( [Acct], [Customer], [Code], [Description], [Sale Person],
[Region], [Store Type]),([Acct]),());

SQL Server Group By with Joins

SELECT
[CustomerKey] AS 'Cust #',
CU.[CompanyName] AS 'Company Name',
ISS.InvoiceDate AS 'Invoice Date',
ISS.InvoiceTotal AS 'Invoice Total',
ISNULL(CU.ShopPhone,'') AS 'Company Shop',
ISNULL(CU.CellPhone,'') AS 'Company Cell',
ISNULL(CU.OfficePhone,'') AS 'Company Office',
ISNULL(CF.FirstName, '') AS 'FName',
ISNULL(CF.LastName,'') AS 'LName',
ISNULL(CF.WorkPhone,'') AS 'Contact Work',
ISNULL(CF.CellPhone,'') AS 'Contact Cell',
ISNULL(CF.HomePhone,'') AS 'Contact Home',
ISNULL(CF.EMail,'') AS 'Contact Email',
PSO.OutsidePartsSalespersonName
FROM
[ProfitMaster].[dbo].[vwAC_SSR_Customer] CU with (nolock)
LEFT JOIN
[ProfitMaster].[dbo].[vwAC_SSR_InvoiceSalesSummary] ISS with (nolock) ON CU.CustomerKey = ISS.Customer
JOIN
[ProfitMaster].[dbo].[vwSV_INV_PartsSalesOrder] PSO with (nolock) ON PSO.PartsSalesOrderInvoiceID = ISS.PartsSalesOrderInvoiceID
LEFT JOIN
(SELECT
EntityID, FirstName, LastName, WorkPhone, CellPhone, HomePhone, EMail
FROM
[ProfitMaster].[dbo].[vwGB_CON_ContactFull] with (nolock)
WHERE
EntityID IS NOT NULL
AND FirstName <> ''
AND EntityTypeID = '3'
AND SetDefault = '1'
GROUP BY
EntityID, FirstName, LastName, WorkPhone, CellPhone, HomePhone, EMail) AS CF ON CU.CustomerID = CF.EntityID
WHERE
CU.Inactive = '0'
AND ISS.InvoiceType = 'Parts Order'
AND ISS.InvoiceDate BETWEEN '2017-02-01 00:00:00.000' AND '2017-03-31 3:59:59.000'
AND CU.CustomerBaseBranchID = '1'
AND PSO.OutsidePartsSalespersonName IN ('Dave Freeland', 'Mark Miller', 'Ryan Oaks')
GROUP BY
CU.CustomerKey, CU.[CompanyName],
ISS.InvoiceDate, ISS.InvoiceTotal,
CU.ShopPhone, CU.CellPhone, CU.OfficePhone,
CF.FirstName, CF.LastName, CF.WorkPhone, CF.CellPhone,
CF.HomePhone, CF.EMail, PSO.OutsidePartsSalespersonName
ORDER BY
CU.CompanyName, ISS.InvoiceDate
How can I group this to SUM ISS.InvoiceTotal grouped by CustomerKey?
I keep getting the "is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause." error.
Any ideas?
If you SUM() in the ISS table you can't select from it or add it to the GROUP BY.
SELECT
[CustomerKey] AS 'Cust #',
CU.[CompanyName] AS 'Company Name',
LAST(ISS.InvoiceDate) AS 'Invoice Date',
SUM(ISS.InvoiceTotal) AS 'Invoice Total',
ISNULL(CU.ShopPhone,'') AS 'Company Shop',
ISNULL(CU.CellPhone,'') AS 'Company Cell',
ISNULL(CU.OfficePhone,'') AS 'Company Office',
ISNULL(CF.FirstName, '') AS 'FName',
ISNULL(CF.LastName,'') AS 'LName',
ISNULL(CF.WorkPhone,'') AS 'Contact Work',
ISNULL(CF.CellPhone,'') AS 'Contact Cell',
ISNULL(CF.HomePhone,'') AS 'Contact Home',
ISNULL(CF.EMail,'') AS 'Contact Email',
PSO.OutsidePartsSalespersonName
FROM
[ProfitMaster].[dbo].[vwAC_SSR_Customer] CU with (nolock)
LEFT JOIN
[ProfitMaster].[dbo].[vwAC_SSR_InvoiceSalesSummary] ISS with (nolock) ON CU.CustomerKey = ISS.Customer
JOIN
[ProfitMaster].[dbo].[vwSV_INV_PartsSalesOrder] PSO with (nolock) ON PSO.PartsSalesOrderInvoiceID = ISS.PartsSalesOrderInvoiceID
LEFT JOIN
(SELECT
EntityID, FirstName, LastName, WorkPhone, CellPhone, HomePhone, EMail
FROM
[ProfitMaster].[dbo].[vwGB_CON_ContactFull] with (nolock)
WHERE
EntityID IS NOT NULL
AND FirstName <> ''
AND EntityTypeID = '3'
AND SetDefault = '1'
GROUP BY
EntityID, FirstName, LastName, WorkPhone, CellPhone, HomePhone, EMail) AS CF ON CU.CustomerID = CF.EntityID
WHERE
CU.Inactive = '0'
AND ISS.InvoiceType = 'Parts Order'
AND ISS.InvoiceDate BETWEEN '2017-02-01 00:00:00.000' AND '2017-03-31 3:59:59.000'
AND CU.CustomerBaseBranchID = '1'
AND PSO.OutsidePartsSalespersonName IN ('Dave Freeland', 'Mark Miller', 'Ryan Oaks')
GROUP BY
CU.CustomerKey, CU.[CompanyName],
CU.ShopPhone, CU.CellPhone, CU.OfficePhone,
CF.FirstName, CF.LastName, CF.WorkPhone, CF.CellPhone,
CF.HomePhone, CF.EMail, PSO.OutsidePartsSalespersonName
ORDER BY
CU.CompanyName

Creating BigQuery Statement with multi-table joins

I have been having trouble with BigQuery, I think I am missing a parthesis somewhere:
SELECT
timestamp,
REGEXP_EXTRACT(Analyte.id,r'^Patient, (\d+)') as patientId,
Analyte.contextId as contextId,
Analyte.analyteServiceCode as analyteServiceCode,
Analyte.resultRefRangeLow as analyteLowValue,
Analyte.resultRefRangeHigh as analyteHighValue,
Analyte.resultValue as resultValue
FROM [lustgarten_sandbox.Analyte] as Analyte
join (
SELECT
AnalyteMapping.CONTEXTID as contextId,
AnalyteMapping.CODE as analyteServiceCode,
AnalyteName.NAME
FROM [lustgarten_sandbox.AnalyteMapping] as AnalyteMapping
join [lustgarten_sandbox.AnalyteName] as AnalyteName
on AnalyteName.id = AnalyteMapping.id
where upper(AnalyteName.NAME) = 'Analyte' ) as SpecificAnalyte
on SpecificAnalyte.contextId = Analyte.contextId
and SpecificAnalyte.analyteServiceCode = Analyte.analyteServiceCode
join
SELECT
ldePatientId as ptID,
origBreedCode,
speciesId,
origBreedName,
origSpeciesCode,
breedId,
birthDate.string,
birthDate.date_time,
Analyte.timestamp,
Analyte.patientId,
Analyte.contextId,
Analyte.analyteServiceCode as analyteServiceCode,
Analyte.analyteLowValue, Analyte.analyteHighValue,
Analyte.resultValue
FROM [lustgarten_sandbox.Patient] as Patient
on Analyte.patientId = Patient.ptID
where
Patient.ptID IS NOT NULL
AND Patient.speciesId IS NOT NULL Limit 12000;
If someone could help me out, since I can't seem to find the error. Let me know where I went wrong!
Let me prettify the query:
SELECT
timestamp,
REGEXP_EXTRACT(Analyte.id,
r'^Patient,
(\d+)') AS patientId,
Analyte.contextId AS contextId,
Analyte.analyteServiceCode AS analyteServiceCode,
Analyte.resultRefRangeLow AS analyteLowValue,
Analyte.resultRefRangeHigh AS analyteHighValue,
Analyte.resultValue AS resultValue
FROM
[lustgarten_sandbox.Analyte] AS Analyte
JOIN (
SELECT
AnalyteMapping.CONTEXTID AS contextId,
AnalyteMapping.CODE AS analyteServiceCode,
AnalyteName.NAME
FROM
[lustgarten_sandbox.AnalyteMapping] AS AnalyteMapping
JOIN
[lustgarten_sandbox.AnalyteName] AS AnalyteName
ON
AnalyteName.id = AnalyteMapping.id
WHERE
UPPER(AnalyteName.NAME) = 'Analyte'
) AS SpecificAnalyte
ON
SpecificAnalyte.contextId = Analyte.contextId
AND SpecificAnalyte.analyteServiceCode = Analyte.analyteServiceCode
JOIN
SELECT
ldePatientId AS ptID,
origBreedCode,
speciesId,
origBreedName,
origSpeciesCode,
breedId,
birthDate.string,
birthDate.date_time,
Analyte.timestamp,
Analyte.patientId,
Analyte.contextId,
Analyte.analyteServiceCode AS analyteServiceCode,
Analyte.analyteLowValue,
Analyte.analyteHighValue,
Analyte.resultValue
FROM
[lustgarten_sandbox.Patient] AS Patient
ON
Analyte.patientId = Patient.ptID
WHERE
Patient.ptID IS NOT NULL
AND Patient.speciesId IS NOT NULL
LIMIT
12000;
"Error: Encountered " "JOIN" "JOIN "" at line 30, column 1. Was expecting: "
The problem is easier to spot now: The sub-query that joins Patient needs parenthesis:
Like this:
SELECT
timestamp,
REGEXP_EXTRACT(Analyte.id,
r'^Patient,
(\d+)') AS patientId,
Analyte.contextId AS contextId,
Analyte.analyteServiceCode AS analyteServiceCode,
Analyte.resultRefRangeLow AS analyteLowValue,
Analyte.resultRefRangeHigh AS analyteHighValue,
Analyte.resultValue AS resultValue
FROM
[lustgarten_sandbox.Analyte] AS Analyte
JOIN (
SELECT
AnalyteMapping.CONTEXTID AS contextId,
AnalyteMapping.CODE AS analyteServiceCode,
AnalyteName.NAME
FROM
[lustgarten_sandbox.AnalyteMapping] AS AnalyteMapping
JOIN
[lustgarten_sandbox.AnalyteName] AS AnalyteName
ON
AnalyteName.id = AnalyteMapping.id
WHERE
UPPER(AnalyteName.NAME) = 'Analyte'
) AS SpecificAnalyte
ON
SpecificAnalyte.contextId = Analyte.contextId
AND SpecificAnalyte.analyteServiceCode = Analyte.analyteServiceCode
JOIN (
SELECT
ldePatientId AS ptID,
origBreedCode,
speciesId,
origBreedName,
origSpeciesCode,
breedId,
birthDate.string,
birthDate.date_time,
Analyte.timestamp,
Analyte.patientId,
Analyte.contextId,
Analyte.analyteServiceCode AS analyteServiceCode,
Analyte.analyteLowValue,
Analyte.analyteHighValue,
Analyte.resultValue
FROM
[lustgarten_sandbox.Patient]) AS Patient
ON
Analyte.patientId = Patient.ptID
WHERE
Patient.ptID IS NOT NULL
AND Patient.speciesId IS NOT NULL
LIMIT
12000;
Now we have "Error: 28.1 - 0.0: A query cannot have multiple JOIN clauses".
The only remaining step is to move said JOIN into a subquery (like you already did with "AnalyteName.id = AnalyteMapping.id") for it to work.
For example:
(I don't have the data or table structures to be sure)
SELECT
ptID,
origBreedCode,
speciesId,
origBreedName,
origSpeciesCode,
breedId,
birthDate.string,
birthDate.date_time,
Analyte.timestamp,
Analyte.patientId,
Analyte.contextId,
Analyte.analyteServiceCode AS analyteServiceCode,
Analyte.analyteLowValue,
Analyte.analyteHighValue,
Analyte.resultValue
FROM (
SELECT
timestamp,
REGEXP_EXTRACT(Analyte.id,
r'^Patient,
(\d+)') AS patientId,
Analyte.contextId AS contextId,
Analyte.analyteServiceCode AS analyteServiceCode,
Analyte.resultRefRangeLow AS analyteLowValue,
Analyte.resultRefRangeHigh AS analyteHighValue,
Analyte.resultValue AS resultValue
FROM
[lustgarten_sandbox.Analyte] AS Analyte
JOIN (
SELECT
AnalyteMapping.CONTEXTID AS contextId,
AnalyteMapping.CODE AS analyteServiceCode,
AnalyteName.NAME
FROM
[lustgarten_sandbox.AnalyteMapping] AS AnalyteMapping
JOIN
[lustgarten_sandbox.AnalyteName] AS AnalyteName
ON
AnalyteName.id = AnalyteMapping.id
WHERE
UPPER(AnalyteName.NAME) = 'Analyte'
) AS SpecificAnalyte
ON
SpecificAnalyte.contextId = Analyte.contextId
AND SpecificAnalyte.analyteServiceCode = Analyte.analyteServiceCode
) Analyte
JOIN (
SELECT
ldePatientId AS ptID,
speciesId
FROM
[lustgarten_sandbox.Patient]) AS Patient
ON
Analyte.patientId = Patient.ptID
WHERE
Patient.ptID IS NOT NULL
AND Patient.speciesId IS NOT NULL
LIMIT
12000;
You missed a couple of parantheses. Look for my comments in the code:
SELECT
timestamp,
REGEXP_EXTRACT(Analyte.id,r'^Patient, (\d+)') as patientId,
Analyte.contextId as contextId,
Analyte.analyteServiceCode as analyteServiceCode,
Analyte.resultRefRangeLow as analyteLowValue,
Analyte.resultRefRangeHigh as analyteHighValue,
Analyte.resultValue as resultValue
FROM
[lustgarten_sandbox.Analyte] as Analyte
JOIN
(
SELECT
AnalyteMapping.CONTEXTID as contextId,
AnalyteMapping.CODE as analyteServiceCode,
AnalyteName.NAME
FROM
[lustgarten_sandbox.AnalyteMapping] as AnalyteMapping
JOIN
[lustgarten_sandbox.AnalyteName] as AnalyteName
ON AnalyteName.id = AnalyteMapping.id
WHERE
upper(AnalyteName.NAME) = 'Analyte'
) as SpecificAnalyte
ON SpecificAnalyte.contextId = Analyte.contextId
AND SpecificAnalyte.analyteServiceCode = Analyte.analyteServiceCode
JOIN
( -- Added This
SELECT
ldePatientId as ptID,
origBreedCode,
speciesId,
origBreedName,
origSpeciesCode,
breedId,
birthDate.string,
birthDate.date_time,
Analyte.timestamp,
Analyte.patientId,
Analyte.contextId,
Analyte.analyteServiceCode as analyteServiceCode,
Analyte.analyteLowValue,
Analyte.analyteHighValue,
Analyte.resultValue
FROM
[lustgarten_sandbox.Patient] as Patient
ON Analyte.patientId = Patient.ptID
WHERE
Patient.ptID IS NOT NULL AND
Patient.speciesId IS NOT NULL
) Patient -- Added This
LIMIT 12000;