How to combine two sql queries into one - sql

How can I combine these two SQL statements?
SELECT SUM(hits01 + hits02 + hits03 + hits04 + hits05 + hits06 + hits07 + hits08 + hits09) AS 'AEROwiz'
FROM tbl_2011
WHERE appName='AEROwiz'
SELECT SUM(hits10 + hits11 + hits12) AS 'AEROwiz'
FROM tbl_2010
WHERE appName='AEROwiz'
hits10, hits11 and hits12 exist in both tables.

Use a UNION query - just stuff "UNION" between the two queries:
SELECT SUM(...) AS AEROWiz
FROM ...
UNION
SELECT SUM(...) AS AEROWiz
FROM ...
update
wrap the union in yet another query:
SELECT SUM(AEROWiz)
FROM (
.... unioned queries here
) AS child

SELECT SUM(hits01 + hits02 + hits03 + hits04 + hits05 + hits06 +
hits07 + hits08 + hits09) AS 'AEROwiz'
FROM tbl_2011
WHERE appName='AEROwiz'
UNION ALL
SELECT SUM(hits10 + hits11 + hits12) AS 'AEROwiz'
FROM tbl_2010
WHERE appName='AEROwiz'
Use UNION ALL as it will allow duplicates, and UNION will not put duplicates in the query result. With the SUM() aggregate, I'm guessing there's a good chance of duplication summations, so I'd go with UNION ALL for this one.

You could use two subselects:
SELECT
(
SELECT SUM(hits01 + hits02 + hits03 + hits04 + hits05 + hits06 + hits07 + hits08 + hits09)
FROM tbl_2011
WHERE appName='AEROwiz'
) T1
+
(
SELECT SUM(hits10 + hits11 + hits12)
FROM tbl_2010
WHERE appName='AEROwiz'
) T2
AS AEROwiz
You may also want to consider normalizing your database so that you don't have a table for each year.

SELECT SUM(hits01 + hits02 + hits03 + hits04 + hits05 + hits06 +
hits07 + hits08 + hits09 + t2010.hits10 + t2010.hits11 + t2010.hits12) AS 'AEROwiz'
FROM tbl_2010 t2010
JOIN tbl_2011 t2011 ON t2010.appName = t2011.appName
WHERE t2010.appName='AEROwiz'

Related

SQL Pivot - take a changing date from column and make it a row header

I have a basic query that looks like this.
SELECT Database_Name,
FilingDate,
SUM(ISNULL([column1], 0) + ISNULL(column2], 0) +
ISNULL([column3], 0) + ISNULL([column4], 0)) AS Total
FROM SomeTable(NOLOCK)
GROUP BY Database_Name,
FilingDate
ORDER BY Database_Name,
FilingDate DESC
This query outputs results that look like this.
I would like to take the dates returned in the FilingDate column and use them as new column headers with the totals for each database and date being used as the row content. The end result should look like this:
My research suggests that a pivot is the best option but I'm struggling to find the right way to execute it as my dates change each day Any assistance would be appreciated.
If this is MS SQL, you can use a dynamic pivot table. Here is a solution using your query (should work, but I don't have the base data to test it).
SELECT Database_Name,
FilingDate,
SUM( ISNULL(column1 ,0) +
ISNULL(column2],0) +
ISNULL([column3],0) +
ISNULL([column4],0)
) AS Total
INTO #T1
FROM SomeTable(NOLOCK)
GROUP BY Database_Name,
FilingDate
DECLARE #PivotColumnHeaders varchar(MAX)
SELECT #PivotColumnHeaders =
COALESCE(
#PivotColumnHeaders + ',[' + CAST(UC.FilingDate AS NVARCHAR(10)) + ']',
'[' + CAST(UC.FilingDate AS NVARCHAR(10)) + ']'
)
FROM (SELECT FilingDate FROM #T1 GROUP BY FilingDate) UC
DECLARE #PQuery varchar(MAX) = '
SELECT * FROM (SELECT Database_Name, FilingDate, Total FROM #T1 T0) T1
PIVOT (SUM([Total]) FOR FilingDate IN (' + #PivotColumnHeaders + ') ) AS P'
EXECUTE (#PQuery)
DROP TABLE #T1

Ordering SQL SELECT by result of a string comparison

I have a table with two string columns, ID and LANGUAGE. Language can be one of CYM, ENG, GAE.
When selecting data from the table, I want to order it by the language column, putting a specified language at the start of the results, with the other languages later, in any order.
Say I have the data
+===+=====+
+ 1 + CYM +
+ 2 + GAE +
+ 3 + ENG +
+ 4 + CYM +
+===+=====+
and I want the output to be
+===+=====+
+ 3 + ENG +
+ 1 + CYM +
+ 2 + GAE +
+ 4 + CYM +
+===+=====+
How do I do the equivalent of
SELECT ID, LANGUAGE
FROM TABLE
ORDER BY (LANGUAGE = 'ENG'), ID
You can use CASE WHEN to ensure ENG will be first:
SELECT ID, LANGUAGE
FROM your_table
ORDER BY
CASE LANGUAGE WHEN 'ENG' THEN 0
ELSE 1
END ASC;
-- ,ID ASC -- if needed
LiveDemo

SQL Group By Query

I have the following table with one column ArbPlWPos:
+------------+
+ IH-MKE +
+ IH-MKEEA +
+ IH-MKEEB +
+ IH-MKEPE +
+ IH-MKEPM +
+ IH-MVKE1 +
+ IH-MVKM1 +
+------------+
I can run a statement in MS Access which groups by the first 6 letters:
SELECT left(ArbPlWPos, 6), count(left(ArbPlWPos, 6))
FROM my_table
GROUP BY left(ArbPlWPos, 6)
+------------+------+
+ IH-MKE + 10 +
+ IH-MKM + 20 +
+ IH-MVK + 30 +
+------------+------+
How to include the IH-MVK into the IH-MKE, so the result should be:
+------------+------+
+ IH-MKE + 40 +
+ IH-MKM + 20 +
+------------+------+
Is this somehow possible with SQL/Access?
In MS Access, you can do this using a conditional expression, iif():
SELECT iif(ArbPlWPos like "IH-MVK*", "IH-MKE", left(ArbPlWPos, 6)),
count(*)
FROM TABLE
GROUP BY iif(ArbPlWPos like "IH-MVK*", "IH-MKE", left(ArbPlWPos, 6));
You can group by any expression, but you are to repeat it after SELECT (is you need) and after GROUP BY as you did with an usual column. For example:
SELECT my_function_or_expression(column_A, column_B), count(1)
FROM my_table
GROUP BY my_function_or_expression(column_A, column_B);
In your case it will be:
SELECT
CASE WHEN left(ArbPlWPos, 6) = 'IH-MVK'
THEN 'IH-MKE'
ELSE left(ArbPlWPos, 6) END AS cutArbPlWPos,
count(1) AS amount
FROM my_table
GROUP BY CASE WHEN left(ArbPlWPos, 6) = 'IH-MVK'
THEN 'IH-MKE'
ELSE left(ArbPlWPos, 6) END;
You can also simplify it using subquery.
SELECT cutArbPlWPos, count(1)
FROM (SELECT
CASE WHEN left(ArbPlWPos, 6) = 'IH-MVK'
THEN 'IH-MKE'
ELSE left(ArbPlWPos, 6) END AS cutArbPlWPos
FROM my_table
)
GROUP BY cutArbPlWPos;

SQL MAX problems in query

Can anyone tell me why this isn't working? It's giving me ALL the visit dates and I'm just looking for the most recent visit date:
SELECT ID , MAX(CAST((CAST(VISITMO AS nvarchar(2)) + '/' +
CAST(VISITDAY AS nvarchar(2)) + '/' +
CAST(VISITYR AS nvarchar(4))) AS date)
) AS LastVisitDATE
FROM [VisitTable]
WHERE ID IN (SELECT ID FROM Table2 WHERE other criteria is met)
GROUP BY ID, VISITYR, VISITMO, VISITDAY
I kept adding to the GROUP BY statement because of the errors I got
SELECT ID , MAX(CAST((CAST(VISITMO AS nvarchar(2)) + '/' +
CAST(VISITDAY AS nvarchar(2)) + '/' +
CAST(VISITYR AS nvarchar(4))) AS date)
) AS LastVisitDATE
FROM [VisitTable]
GROUP BY ID

Added a few lines of code and now query is taking 5x as long to run. Executions plans are almost identical

I have a query that has been in production a long time and takes an average of 4 seconds to run. I added the code below which is a declaration of a table and then an insert into that table. then the select query joins to that and returns 1 field from it in the select statement. Now the query takes up to 25 seconds to run.
DECLARE #tmpStageLoc TABLE
(
LP VARCHAR(20) ,
stgloc VARCHAR(20)
)
INSERT INTO #tmpStageLoc
EXEC dbo.spGetStageLoc #ActLP = #LP;
--Try to get data from DW tables first.
INSERT INTO [COMMON_INFORMATION].[dbo].[ProcTmpData]
( SPID ,
DataSetName ,
IntValue1 , --JRB004
ChValue1 , --JRB001
String1 ,
InsDate
)
SELECT DISTINCT
##SPID ,
#datasetname ,
ls.ToDC ,
col.Cust_No --JRB001
,
REPLACE(#LOADNUM, ' ', '') + --JRB007
'~' + 'N/A'
+ --JRB005 Wave number no longer printed on label
'~' + CASE WHEN la.stage_loc IS NULL THEN ''
ELSE la.stage_loc + '-' + ISNULL(la.misc_info,
'')
END + '~' + fa.OrderControlNo + '~' + col.Cust_No
+ '~' + SUBSTRING(cst.name, 1, 20) + '~'
+ SUBSTRING(cst.name, 21, 5) + '~' + LEFT(cst.address1
+ ', '
+ CASE
WHEN cst.address2 IS NULL
THEN ''
ELSE ( cst.address2
+ ', ' )
END + cst.city
+ ', '
+ cst.state, 45)
+ '~' + ls.StopNO + '~' + ls.LoadNo + '~' + e.first_name
+ ' ' + e.last_name + --JRB009
'~' + --JRB009
CASE WHEN cst.plt_usage IS NULL --JRB009
THEN '' --JRB009
ELSE --JRB009
'# ' + LEFT(cst.plt_usage, 20) --JRB009
END + '~' + ISNULL(STG.STGLOC, '') + '~' --JRB009
,
#RUNDTE
FROM dbo.tblFactAction AS fa
LEFT OUTER JOIN COMMON_INFORMATION.dbo.LoadStop AS ls ON LEFT(fa.OrderControlNo,
8) = ls.ExtOrderNo
AND ls.LatestLoadFlg = 1 --JRB008
LEFT OUTER JOIN dbo.RP_LaneAssign AS la ON ls.LoadNo = la.carrier_move_id
OR ls.ExtOrderNo = la.order_num
LEFT OUTER JOIN dbo.Cust_Order_Lookup AS col ON fa.OrderControlNo = col.Order_Control_no
LEFT OUTER JOIN COMMON_INFORMATION.dbo.Partners AS cst ON col.Cust_No = cst.partner_shipto
LEFT OUTER JOIN COMMON_INFORMATION.dbo.Employee AS e ON fa.EmployeeID = CAST(e.emp_no AS VARCHAR(40))
LEFT OUTER JOIN #tmpStageLoc STG ON fa.actlp = STG.LP
WHERE fa.ActLP = #LOADNUM
AND fa.AssignTypeID IN ( 'PB01', 'PF01' )
I have looked at the execution plans in SQL Sentry Plan Explorer and they look almost identical. I am using the free version of the software. I am at a loss at why the query takes so long to run. just an FYI when I execute the stored procedure that is being called it runs instantly.
Any ideas on how I can figure out why the query now runs for so long?