Calculation returning wrong resutls - nested

I am created a calculation using two calculationsi n Tableau The results returned are incorrect. But each piece of the calculation returns the correct number.
Cal 1:
If YEAR([TRANSACTION_DATE ) = YEAR(TODAY()) AND [TRANSACTION_DATE (Custom SQL Query)]< TODAY() THEN [Handled] END
Results: 57,619
Cal 2:
`If YEAR([TRANSACTION_DATE (Custom SQL Query)]) = YEAR(TODAY())
AND [TRANSACTION_DATE (Custom SQL Query)]< TODAY()
and [Contact Type His]= 'CHAT Agt' THEN [AS ACTIVE TIME (S)]/3600
ELSEIF YEAR([TRANSACTION_DATE (Custom SQL Query)]) = YEAR(TODAY())
AND [TRANSACTION_DATE (Custom SQL Query)]< TODAY()
and[Contact Type His] = 'BLENDED Agt' Then [Busy Time (S)]/3600 end`
Results: 6,012
Final Calculation: CAL 1 /CAL 2
Results 20997.79 expecting 9.58
Can someone tell me what I am doing wrong.

If you want to calculate these aggregations without any further level of detail, use this calculation
COL1
{SUM(
If YEAR([TRANSACTION_DATE ) = YEAR(TODAY()) AND [TRANSACTION_DATE (Custom SQL Query)]< TODAY() THEN [Handled] END
)}
COL2
{SUM(
If YEAR([TRANSACTION_DATE (Custom SQL Query)]) = YEAR(TODAY())
AND [TRANSACTION_DATE (Custom SQL Query)]< TODAY()
and [Contact Type His]= 'CHAT Agt' THEN [AS ACTIVE TIME (S)]/3600
ELSEIF YEAR([TRANSACTION_DATE (Custom SQL Query)]) = YEAR(TODAY())
AND [TRANSACTION_DATE (Custom SQL Query)]< TODAY()
and[Contact Type His] = 'BLENDED Agt' Then [Busy Time (S)]/3600 end
)}
and then Col1/Col2

Related

Run complex SQL queries using python

I am trying to run this SQL query by connecting pyodbc and SQL Server. The query selects columns from existing tables and performs a select into a global temp table.
sql_extract_query = """SELECT left(convert(varchar(8),dim_orderdate_key,112),6) as forYYYYMM,
CASE
WHEN ForProfile IN ('AA','AB','AC','AD','AE') then 'Stage 1'
WHEN ForProfile IN ('AF','AG','AH','AI') then 'Stage 2'
END AS VODAUK_Stage,
hasPaymentOK,
amount,
CASE
WHEN amount>0 AND amount <=50 THEN 'A £0000-£0050'
WHEN amount>50 AND amount<=100 THEN 'B £0050-£0100'
WHEN amount>100 AND amount<=150 THEN 'C £0100-£0150'
WHEN amount>150 AND amount<=200 THEN 'D £0150-£0200'
WHEN amount>2500 THEN 'I £2500+'
END AS ABC_Amt_Bucket,
CustID,
sumPaymentPaidAmount
INTO ##tmpCaseResult
FROM db as CR WITH (NOLOCK)
inner join db.[ConsumerAccount] byConsAcc on byConsAcc.consumeraccount_key = [CR].consumeraccount_key
inner join db.[CustomerAccount] byCustAcc on byCustAcc.customeraccount_key = [CR].customeraccount_key
WHERE byCustAcc.ForCustomer = 'ABC' AND
[amount] > 0 AND
CR.orderdate_key >= cast(convert(char(6),dateadd(month,-18,getdate()),112)+'01' as int)
AND [ForProfile] like 'A%';"""
Wondering if there exist any ways to run this complex query? I have tried with pyodbc and pymssql, but the temp table was not created.
Any suggestion please?

SQL Server date range search issue

I have a MS SQL Server DateTime field, and Im trying to search all records that are in between a date range:
mySqlString = "select * from users where signupDate >=#from and signupdate <=#to"
The two variables containing the date range come with format MM/dd/yyyy (dataFrom and dataTo, so Im replacing #from and #to at the string as follows:
datefrom = new Date(dataFrom);
dateto = new Date(dataTo);
req.input('from', sql.DateTime, datefrom )
req.input('to', sql.DateTime, dateto )
But I do not get any result.
What's the best approach to get this working properly?
You can always use CONVERT to accommodate your SQL query to your input format. In your case its format 101: select convert(varchar, getdate(), 101) ---> mm/dd/yyyy
So your query should look like
where (signupdate >= CONVERT(date, #from, 101)) AND (signupdate <= CONVERT(date, #to, 101))
This way you won't worry about the time of the stored date
req.input('from', sql.Date, (dataFrom))
req.input('to', sql.Date, (dataTo))
Assuming you checked if dataFrom and dataTo have valid dates.

Remove decimal places from varchar(32) result

I'm using SQL and windows batch script to download inventory from our POS and then upload it to a 3rd party platform. The file is successfully downloading and uploading, but the 3rd party platform is quite finicky on formatting. Specifically, it won't accept decimal place for the column titled "Quantity".
I've searched and tried various different approaches but can't seem to find one that works. The tricky aspect to this sql is that i had to use a join in order to create a title row and I'm using the format varchar(32) I've posted my sql below, any suggestions?
set nocount ON
SELECT CAST('sku' as VARCHAR(32)) AS sku,
CAST('quantity' as VARCHAR(32)) AS quantity
UNION
SELECT CAST(IM_BARCOD.BARCOD AS
VARCHAR(32)) as sku, case when
IM_INV.QTY_AVAIL > 0 then
CAST(IM_INV.QTY_AVAIL AS VARCHAR(32)) else
CAST(0 as VARCHAR(32)) END as quantity
FROM IM_BARCOD INNER JOIN IM_INV ON
IM_INV.ITEM_NO = IM_BARCOD.ITEM_NO INNER
JOIN IM_PRC ON IM_INV.ITEM_NO =
IM_PRC.ITEM_NO INNER JOIN
IM_ITEM ON IM_INV.ITEM_NO = IM_ITEM.ITEM_NO
UNION
SELECT CAST(IM_BARCOD.BARCOD AS
VARCHAR(32)) as sku, case when
IM_INV_CELL.QTY_AVAIL > 0 then
CAST(IM_INV_CELL.QTY_AVAIL AS VARCHAR(32))
else CAST (0 as VARCHAR (32)) END as
quantity FROM IM_BARCOD INNER JOIN IM_PRC
ON IM_BARCOD.ITEM_NO = IM_PRC.ITEM_NO INNER
JOIN IM_INV_CELL ON IM_BARCOD.ITEM_NO =
IM_INV_CELL.ITEM_NO AND
IM_INV_CELL.DIM_1_UPR=IM_BARCOD.DIM_1_UPR
AND IM_INV_CELL.DIM_2_UPR =
IM_BARCOD.DIM_2_UPR AND
IM_INV_CELL.DIM_3_UPR =IM_BARCOD.DIM_3_UPR
INNER JOIN
IM_ITEM ON IM_BARCOD.ITEM_NO =
IM_ITEM.ITEM_NO

Getting error while running an sql script in ADW

Am getting an error that goes like this:
Insert values statement can contain only constant literal values or variable references.
these are the statements in which I am getting the errors:
INSERT INTO val.summary_numbers (metric_name, metric_val, dt_create) VALUES ('Total IP Enconters',
(SELECT
count(DISTINCT encounter_id)
FROM prod.encounter
WHERE encounter_type = 'Inpatient')
,
(SELECT min(mod_loadidentifier)
FROM ccsm.stg_demographics_baseline)
);
INSERT INTO val.summary_numbers (metric_name, metric_val, dt_create) VALUES ('Total 30d Readmits',
(SELECT
count(DISTINCT encounter_id)
FROM prod.encounter_attr
WHERE
attr_name = 'day_30_readmit' AND attr_value = 1)
,
(SELECT min(mod_loadidentifier)
FROM ccsm.stg_demographics_baseline));
Change your query like this:
insert into val.summary_numbers
select
'Total IP Enconters',
(select count(distinct encounter_id)
from prod.encounter
where encounter_type = 'Inpatient'),
(select min(mod_loadidentifier)
from ccsm.stg_demographics_baseline)
When using the ADW service, I would recommend that you consider using the CTAS operation possibly combined with a RENAME. The RENAME is a metadata operation so it is fast and the CTAS is parallel where the INSERT INTO will be row by row.
You may still have a data related issue that can be hard to determine with out the create table statement.
Thanks

View Measure definition (DAX) in excel

I am fairly new to DAX and to SSAS-Tabular, so I hope that you'll forgive any ignorance.
We have an SSAS-Tabular cube and we're using it in Excel to see the data (pivot table). Is there a way for me to view the DAX behind a measure in Excel?
Thanks,
Eli
In Excel, go to the 'Data' tab, click on 'New Query', select 'from Database', select 'from SQL Server Analysis Services database'.
Put in the name of the server, and the name of the database (name of the cube).
Click the dropdown next to "MDX or DAX query (optional)".
Add the following query (note that this is DMX, not MDX or DAX, but it will work - note that if you don't edit the catalog name to match your cube, it won't return any data):
SELECT
[MEASUREGROUP_NAME] AS [Table Name],
[MEASURE_CAPTION] AS [Measure Name],
[DESCRIPTION] AS [Measure Description],
[EXPRESSION] AS [Measure Logic]
FROM
$SYSTEM.MDSCHEMA_MEASURES
WHERE
[CUBE_NAME] ='Model'
AND
[MEASURE_IS_VISIBLE]
AND
[CATALOG_NAME] = '<enter name of your cube here>'
ORDER BY
[MEASUREGROUP_NAME]
Click "Load".
You now have a page in the spreadsheet that functions as your data dictionary for measures. You can do the same thing, adding queries for dimenions with this code:
SELECT
[DIMENSION_UNIQUE_NAME] AS [Table Name],
HIERARCHY_CAPTION AS [Column Name],
[DESCRIPTION] AS [Column Description]
FROM
$system.MDSchema_hierarchies
WHERE
[CUBE_NAME] = 'Model'
AND
[HIERARCHY_ORIGIN] = 2
AND
[HIERARCHY_IS_VISIBLE]
AND
[CATALOG_NAME] = '<enter name of your cube here>'
ORDER BY
[DIMENSION_UNIQUE_NAME]
And for tables, this code:
SELECT
[DIMENSION_CAPTION] AS [Table Name],
[DESCRIPTION] AS [Table Description]
FROM
$system.MDSchema_Dimensions
WHERE
[CUBE_NAME] ='Model'
AND
[DIMENSION_CAPTION] <> 'Measures'
AND
[CATALOG_NAME] = '<enter name of your cube here>'
ORDER BY
[DIMENSION_CAPTION]
And for hierarchies, this code:
SELECT
[DIMENSION_UNIQUE_NAME] AS [Table Name],
[HIERARCHY_CAPTION] AS [Hierarchy Name],
[DESCRIPTION] AS [Hierarchy Description]
FROM
$system.MDSchema_hierarchies
WHERE
[CUBE_NAME] = 'Model'
AND
[HIERARCHY_ORIGIN] = 1
AND
[CATALOG_NAME] = '<enter name of your cube here>'
ORDER BY
[DIMENSION_UNIQUE_NAME]
If you edit the properties for these queries (use the 'Connections' button on the data tab), you can set this sheet to refresh every time the worksheet is opened (similar to how you probably have your pivot table connections set up), and now you have data dictionary tabs that automatically reflect the most current cube design. Hope this helps!

Resources