Formatting the code from IT to match Power Query / Power BI - sql

Could someone please confirm what code language is it and how do I edit it to fit with Power BI function to import data from SQL Database please?
Got this from IT person but when I try to paste it into Power Query it gives error messages.
SELECT distinct Z.Territory , (z.AccountNumber ) as AccountNumber , (a.AccountType ) as AccountType , (z.CompanyName ) as CompanyName , (z.AccountNumber ) as AccountNumber , (z.CompanyName ) as CompanyName , z.SubscriptionReference ,z.SubscriptionID , (isnull(z.serialnumber,r.SerialNumber) ) as SerialNumber ,case when (rpc.billingperiodalignment) = 'AlignToCharge' then (z.product) else isnull(r.ProductDescription,z.product) end as Description , (r.ProductVersion ) as ProductVersion , (r.CoverExpiryDate ) as CoverExpiryDate , (z.SubscriptionStatus ) as SubscriptionStatus ,z.SubscriptionVersion
--, MAX(z.RenewalTerm) AS RenewalTerm , (z.[SubscriptionTermType]) as [SubscriptionTermType] , (case when z.[UnitofMeasure] = 'Desktop Users' then z.[Quantity] end) as 'Desktop Users' , (z.billingperiod ) as BillingPeriod ,(rpc.BillingPeriodAlignment) BillingPeriodAlignment ,(z.[ContractEffectiveDate]) as ContractEffectiveDate ,(z.TermEndDate) as TermEndDate

It's SQL, but it's invalid, so you'll need to get it fixed. It looks like it got cut off. When it's valid you should be able to paste it into a SQL Server Management Studio query window and test it.
To use it in Power Query use Value.NativeQuery, like this;
let
Source = Sql.Database("localhost", "adventureworks2017"),
Query = "
select *
from Sales.SalesOrderHeader
",
Data = Value.NativeQuery(Source, Query, null, [EnableFolding=true])
in
Data

Related

Can you explain the meaning of a minus in a SQL select statement?

I am working with SQL and I found this snippet, my question is: what does it mean those minus symbols (-) inside the select statement? I know is a kind of some trick, but I can't find information online about how it is used, please any insight would be welcome.
I am referring to:
SELECT - sum(st.sales) AS sales
- sum(st.orders) AS orders
- sum(st.aov) AS aov
It seems to be related to ledger tables, if you have any documentation, blog or pdf please give me the link to check it.
The full SQL looks like this:
INSERT INTO sales_test
WITH source_query AS --find the existing values in the ledger table and invert them
(
SELECT
st.og_date
, st.merchant
, st.store_name
, st.country
, st.kam
, st.class
, st.origin
, - sum(st.sales) AS sales
, - sum(st.orders) AS orders
, - sum(st.aov) AS aov
, et.source_file_name
, et.source_file_timestamp
FROM
sales_test st
INNER JOIN
ext_sales_test et
ON
city_hash(et.og_date, et.merchant, et.store_name, et.country, et.kam, et.class, et.origin) = city_hash(st.og_date, st.merchant, st.store_name, st.country, st.kam, st.class, st.origin)
AND st.og_date = et.og_date
AND st.merchant = et.merchant
GROUP BY
st.og_date
, st.merchant
, st.store_name
, st.country
, st.kam
, st.class
, st.origin
, et.source_file_name
, et.source_file_timestamp
)
, union_query AS --if we union the incoming data with the inverted existing data, we get the difference that needs to be ledgered
(
SELECT *
FROM
source_query
UNION ALL
SELECT *
FROM
ext_sales_text
)
It makes the numeric value negative(if numeric value is negative, - - is positive), in your case it first performs the sum and then it makes it negative or positive:
As an example:
USE tempdb;
GO
DECLARE #Num1 INT;
SET #Num1 = 5;
SELECT #Num1 AS VariableValue, -#Num1 AS NegativeValue;
GO
Result set:
VariableValue NegativeValue
------------- -------------
5 -5
(1 row(s) affected)
Further info here

Group by - Non-group-by expression in select clause

Sorry you will have to bear with me as i am relativly new to SQL. I am querying an ODBC in EXCEL. At the moment my dataset is massive so i am looking to narrow it down by grouping it by company name and date. not all my columns are calculated fields.I have put the Sum on the two i need adding up. When i try to return the data i get the error of Non-group-by expression in select clause
Please can someone help me out.
SELECT
SopOrder_0.SooOrderNumber
, Company_0.CoaCompanyName
, InvoiceCreditItem_0.InvoiceCreditItemID
, InvoiceCreditItem_0.IciInvoiceApproved
, InvoiceCreditItem_0.InvoiceCreditID
, InvoiceCreditItem_0.CompanySiteID
, InvoiceCreditItem_0.VatID
, InvoiceCreditItem_0.NominalID
, InvoiceCreditItem_0.IciCreatedDate
, Sum(InvoiceCreditItem_0.IciTotalNettValue)
, Sum(InvoiceCreditItem_0.IciVatValue)
FROM
SBS.PUB.Company Company_0
, SBS.PUB.Customer Customer_0
, SBS.PUB.InvoiceCreditItem InvoiceCreditItem_0
, SBS.PUB.SopOrder SopOrder_0
WHERE
SopOrder_0.SopOrderID = InvoiceCreditItem_0.SopOrderID
AND InvoiceCreditItem_0.CompanyID = Customer_0.CompanyID
AND InvoiceCreditItem_0.CompanyID = Company_0.CompanyID
AND (Company_0.CoaCompanyName<>'ATOS')
AND InvoiceCreditItem_0.IciCreatedDate >= ?
GROUP BY
Company_0.CoaCompanyName, InvoiceCreditItem_0.IciCreatedDate

How to split a column into two columns based on the value in the another column

I have below data in the Ms SQL server table.
I would like to get the output like below.
I have tried two sets of queries but it didn't helped me.
1st set query gives me the null values
Query
SELECT
[id]
, [sav]
, [cat]
, [tech]
, [asset]
, CASE
WHEN [objname] = 'FieldName'
THEN [stringvalue]
END AS [fieldname]
, CASE
WHEN [objname] = 'FieldValue'
THEN [stringvalue]
END AS [fieldvalue]
FROM [test].[dbo].[sample];
Output
2nd set query gives me 0 as field value, because i have hard coded it.
Query
SELECT
ROW_NUMBER() OVER(ORDER BY [fieldname]) AS 'id'
, [sav]
, [cat]
, [tech]
, [asset]
, [fieldname]
, 0 AS [fieldvalue]
FROM [test].[dbo].[sample] PIVOT(MAX([stringvalue]) FOR [objname] IN(
[fieldname])) [p]
WHERE [fieldname] IS NOT NULL;
Output
How to achieve it ?
You have a very arcane data structure. SQL tables are inherently unordered. From what I can tell, the SQL value is in the "next" row based on the id.
If so, you can use lead():
select . . .,
stringvalue as fieldname, next_string_value as stringvalue
from (select t.*, lead(t.stringvalue) over (order by id) as next_string_value
from t
) t
where t.objname = 'objname';
If you are really using SQL Server 2008, you can use a self-join. This does assume that the ids have no gaps in them.

Get the TFS 2015 Work Item Hierarchy in SQL Server

I'm trying to create a report in Tableau to generate a tree structure of all the work items in TFS 2015 and their respective hierarchy
Such as
Epic->Features->User Story->Task
But repeated attempts to create the sql query have failed. Could you please help me with the SQL query that could help fetch all the work items and display their hierarchy?
Thanks.
Instead of using SQL Query, it's suggested to use TFS REST API to create a query in TFS, the WIQL looks like:
"wiql": "select [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State], [System.Tags] from WorkItemLinks where (Source.[System.TeamProject] = 'xxx' and Source.[System.WorkItemType] <> '' and Source.[System.State] <> '') and ([System.Links.LinkType] = 'System.LinkTypes.Hierarchy-Forward') and (Target.[System.WorkItemType] <> '') order by [System.Id] mode (Recursive)"
So, i have found this query, which is working and can help you create a tableau workbook for the hierarchy:
WITH cte
AS ( SELECT DimTeamProject.ProjectNodeName ,
System_WorkItemType ,
DimWorkItem.System_Id ,
FactWorkItemLinkHistory.TargetWorkItemID ,
DimWorkItem.System_Title,
DimWorkItem.System_State,
DimWorkItem.Microsoft_VSTS_Common_ActivatedDate,
DimWorkItem.Microsoft_VSTS_Scheduling_TargetDate,
DimWorkItem.System_CreatedDate,
DimWorkItemLinkType.LinkName,
TeamProjectSK,
system_rev,
row_number() over( partition by system_id,TeamProjectSK, FactWorkItemLinkHistory.TargetWorkItemID order by system_rev desc ) rownum
FROM DimWorkItem ,
DimTeamProject ,
FactWorkItemLinkHistory,
DimWorkItemLinkType
WHERE DimWorkItem.TeamProjectSK = DimTeamProject.ProjectNodeSK
AND DimWorkItem.System_Id = FactWorkItemLinkHistory.SourceWorkItemID
and DimWorkItemLinkType.WorkItemLinkTypeSK = FactWorkItemLinkHistory.WorkItemLinkTypeSK
/* -To Test the Query using the project Name of our choice- */
--AND ProjectNodeName =
AND System_State in ('ACTIVE','NEW')
/* -System Revisions are created when the entry is modified. Onlt the latest entry will have the below revised date- */
AND System_RevisedDate = '9999-01-01 00:00:00.000'
AND DimWorkItemLinkType.Linkname IN ( 'Parent',
'child' )
GROUP BY DimTeamProject.ProjectNodeName ,
DimWorkItem.System_Id ,
FactWorkItemLinkHistory.TargetWorkItemID ,
DimWorkItem.System_Title ,
System_WorkItemType,
DimWorkItem.System_State,
TeamProjectSK,
DimWorkItemLinkType.LINKName,
DimWorkItem.Microsoft_VSTS_Common_ActivatedDate,
DimWorkItem.Microsoft_VSTS_Scheduling_TargetDate,
DimWorkItem.System_CreatedDate,
system_rev
)
SELECT distinct t1.ProjectNodeName ,
t1.System_Id requirement_Id ,
t1.System_WorkItemType,
t1.System_Title requirement_title ,
t2.System_Id Change_request_id ,
t1.LinkName,
t2.System_Title Change_Request_Title,
t1.Microsoft_VSTS_Common_ActivatedDate,
t1.System_CreatedDate,
t1.Microsoft_VSTS_Scheduling_TargetDate,
t1.System_State,
T1.rownum
FROM cte t1
INNER JOIN cte t2 ON t1.TargetWorkItemID = t2.System_Id
and t1.rownum = 1
ORDER BY t1.System_Id;
Used a CTE to find get the complete hierarchy, its faster and more efficient than the query posted before.

Group by calculated Case column from another table

I have the below code which works correctly however the data isn't in the format that I want to display. The code only works when I group by Plant however this will obviously create multiple PlantGrps. Is it possible to group by the case when statement?
select
Case
When Plant IN(
Select Client From
CO_001_Plants_090_Final
where CustGrp = 'HovisMills'
) Then 'HovisMills'
When Plant IN(
Select Client From
CO_001_Plants_090_Final
where CustGrp = 'HovisBakeries'
) Then 'HovisBakeries'
When Plant IN(
Select Client From
CO_001_Plants_090_Final
where CustGrp = 'HovisGroup'
) Then 'HovisGroup'
end as PlantGrp,
--Type
sum(Line_Val),Count(Material)
FROM dbo.vw_DA_003_ChargingRecord as P
where
Plant IN(select Client
FROM dbo.CO_001_Plants_090_Final
where Upper(CustGrp) = 'HOVIS')
and Charging_Period = '201509'
and Type <> 'Carriage'
group by
Plant, Type